给定两个整数A和B ,任务是找到两个互质数C1和C2 ,使得C1除以A , C2除以B。
例子:
Input: A = 12, B = 16
Output: 3 4
12 % 3 = 0
16 % 4 = 0
gcd(3, 4) = 1
Input: A = 542, B = 762
Output: 271 381
简单方法:一种简单的解决方案是将存储所有A和B的约数的随后迭代所有A和B成对的约数,以找到一对是互质元件。
高效的方法:如果将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