Given two integers A and B representing the time taken by two different Sand timers to get empty. The task is to find the count of flips of each timer till the instance at which both the Sand timers get empty at the same time.
Examples:
Input: A = 30, B = 15
Output: 0 1
After 15 minutes: 15 0
Flip timer 2: 15 15
After another 15 minutes: 0 0
Input: A = 10, B = 8
Output: 3 4
Approach: Lowest Common Factor (LCM) of two number will determine the time at which both the Sand timers will get empty together.
LCM(A, B) = (A * B) / GCD(A, B)
Dividing the LCM by input will give the number of flips for each sand timer respectively.
C++
#include<bits/stdc++.h>
using namespace std;
int gcd( int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
void flip( int a, int b){
int lcm =(a * b)/gcd(a, b);
a = lcm/a;
b = lcm/b;
cout<<a-1<< " " <<b-1;
}
int main(){
int a = 10;
int b = 5;
flip(a, b);
}
|
Java
class GFG
{
static int gcd( int a, int b)
{
if (b == 0 )
return a;
return gcd(b, a % b);
}
static void flip( int a, int b)
{
int lcm = (a * b) / gcd(a, b);
a = lcm / a;
b = lcm / b;
System.out.print((a - 1 ) + " " + (b - 1 ));
}
public static void main(String[] args)
{
int a = 10 ;
int b = 5 ;
flip(a, b);
}
}
|
Python3
def gcd(a, b):
if (b = = 0 ):
return a
return gcd(b, a % b)
def flip(a, b):
lcm = (a * b) / / gcd(a, b)
a = lcm / / a
b = lcm / / b
print (a - 1 , b - 1 )
a = 10
b = 5
flip(a, b)
|
C#
using System;
class GFG
{
static int gcd( int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void flip( int a, int b)
{
int lcm = (a * b) / gcd(a, b);
a = lcm / a;
b = lcm / b ;
Console.WriteLine((a - 1) + " " +
(b - 1));
}
public static void Main()
{
int a = 10;
int b = 5;
flip(a, b);
}
}
|
Javascript
<script>
function gcd(a, b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
function flip(a, b){
let lcm =parseInt((a * b)/gcd(a, b));
a = parseInt(lcm/a);
b = parseInt(lcm/b);
document.write((a-1)+ " " +(b-1));
}
let a = 10;
let b = 5;
flip(a, b);
</script>
|
Time Complexity: O(min(log a, log b))
Auxiliary Space : O(min(log a, log b))