📜  沙漏计时器翻转计数问题

📅  最后修改于: 2021-04-27 20:06:09             🧑  作者: Mango

给定两个整数AB,代表两个不同的Sand计时器变空所花费的时间。任务是找到每个计时器的翻转计数,直到两个Sand计时器同时变空的实例为止。

例子:

方法:两个数字的最低公因数(LCM)将确定两个Sand计时器一起变空的时间。
LCM(A,B)=(A * B)/ GCD(A,B)
用输入除以LCM可以分别得出每个沙粒计时器的翻转次数。

C++
//C++14 implementation of the approach
#include
using namespace std;
  
//Recursive function to return
//the gcd of a and b
int gcd(int a, int b){
    //Everything divides 0
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
  
//Function to print the number of
//flips for both the sand timers
void flip(int a,int b){
    int lcm =(a * b)/gcd(a, b);
    a = lcm/a;
    b = lcm/b;
    cout<


Java
// Java implementation of the approach
class GFG 
{
  
// Recursive function to return
// the gcd of a and b
static int gcd(int a, int b)
{
    // Everything divides 0
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
  
// Function to print the number of
// flips for both the sand timers
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));
}
  
// Driver code
public static void main(String[] args) 
{
    int a = 10;
    int b = 5;
    flip(a, b);
}
} 
  
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach 
  
# Recursive function to return 
# the gcd of a and b 
def gcd(a, b): 
      
    # Everything divides 0 
    if (b == 0): 
        return a 
    return gcd(b, a % b) 
  
# Function to print the number of 
# flips for both the sand timers
def flip(a, b):
    lcm = (a * b) // gcd(a, b)
    a = lcm // a
    b = lcm // b
    print(a - 1, b - 1)
  
# Driver code
a = 10
b = 5
flip(a, b)
  
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
  
class GFG
{
      
    // Recursive function to return
    // the gcd of a and b
    static int gcd(int a, int b)
    {
        // Everything divides 0
        if (b == 0)
        return a;
          
        return gcd(b, a % b);
    }
      
    // Function to print the number of
    // flips for both the sand timers
    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));
    }
      
    // Driver code
    public static void Main()
    {
        int a = 10;
        int b = 5;
        flip(a, b);
    }
}
  
// This code is contributed by AnkitRai01


输出:
0 1