📜  找到两个互质数整数,这样第一个除以A,第二个除以B

📅  最后修改于: 2021-04-22 09:52:50             🧑  作者: Mango

给定两个整数AB ,任务是找到两个互质数C1C2 ,使得C1除以AC2除以B。
例子:

简单方法:一种简单的解决方案是将存储所有AB的约数的随后迭代所有AB成对的约数,以找到一对是互质元件。
高效的方法:如果将d除以gcd(a,b),gcd(a / d,b / d)= gcd(a,b)/ d 。更正式地讲,如果num = gcd(a,b),gcd(a / num,b / num)= 1,(a / num)(b / num)是相对互质的。
因此,为了找到所需的数字,请找到gcd(a,b)并将其存储在变量gcd中。现在所需的数字将是(a / gcd)(b / gcd)
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to find the required numbers
void findNumbers(int a, int b)
{
 
    // GCD of the given numbers
    int gcd = __gcd(a, b);
 
    // Printing the requried numbers
    cout << (a / gcd) << " " << (b / gcd);
}
 
// Driver code
int main()
{
    int a = 12, b = 16;
 
    findNumbers(a, b);
 
    return 0;
}


Java
// Java implementation of the approach
import java.math.*;
 
class GFG
{
    public static int findGCD(int a, int b)
    {
        if(b == 0)
            return a;
        else
            return findGCD(b, a % b);
    }
 
    // Function to find the required numbers
    static void findNumbers(int a, int b)
    {
     
        // GCD of the given numbers
        int gcd = findGCD(a, b);
         
        // Printing the requried numbers
        System.out.println((a / gcd) + " " +
                           (b / gcd));
         
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a = 12, b = 16;
     
        findNumbers(a, b);
    }
}
 
// This code is contributed by Naman_Garg


Python3
# Python3 implementation of the approach
 
# import gcd function from math module
from math import gcd
 
# Function to find the required numbers
def findNumbers(a, b) :
 
    # GCD of the given numbers
    __gcd = gcd(a, b);
 
    # Printing the requried numbers
    print((a // __gcd), (b // __gcd));
 
# Driver code
if __name__ == "__main__" :
 
    a = 12; b = 16;
 
    findNumbers(a, b);
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
 
class GFG
{
    public static int findGCD(int a, int b)
    {
        if(b == 0)
            return a;
        else
            return findGCD(b, a % b);
    }
 
    // Function to find the required numbers
    static void findNumbers(int a, int b)
    {
     
        // GCD of the given numbers
        int gcd = findGCD(a, b);
         
        // Printing the requried numbers
        Console.Write((a / gcd) + " " +
                      (b / gcd));
         
    }
 
    // Driver code
    static public void Main ()
    {
        int a = 12, b = 16;
     
        findNumbers(a, b);
    }
}
 
// This code is contributed by ajit


Javascript


输出:
3 4