使用欧几里德算法求两个数的 GCD 和 LCM 的Java程序
GCD或两个给定数字 A 和 B 的最大公约数是将 A 和 B 完全整除的最大数,即在每种情况下余数为 0。 LCM或两个给定数字 A 和 B 的最小公倍数是可以被 A 和 B 整除的最小数,在每种情况下余数为 0。
两个数的 LCM 可以通过使用 A 和 B 的 GCD 在欧几里德的方法中计算。
LCM(A, B) = (a * b) / GCD(A, B)
例子:
Input : A = 20, B = 30
Output:
GCD = 10
LCM = 60
Explanation:
The highest number which divides 20 and 30 is 10. So the GCD of 20, 30 is 10.
The lowest number that can be divided by 20 and 30, leaving remainder 0 is 60.
So the LCM of 20 and 30 is 60.
Input : A= 33, B= 40
Output:
GCD = 1
LCM = 1320
计算 GCD 的欧几里德算法:
这种计算 GCD 的方法是基于两个数 A 和 B 的 GCD 保持不变的原则,即使较大的数被 A 和 B 的模代替。在这种方法中,我们对 A 和 B 执行 gcd 运算B 反复用 B 替换 A,用 A 和 B 的模数替换 B,直到模数变为 0。
下面是使用欧几里德算法找到两个数的 GCD 和 LCM 的实现:
Java
// Java program to compute
// GCD of two numbers
// using Euclid's algorithm
import java.io.*;
class GFG {
// gcd method returns the GCD of a and b
static int gcd(int a, int b) {
// if b=0, a is the GCD
if (b == 0)
return a;
// call the gcd() method recursively by
// replacing a with b and b with
// modulus(a,b) as long as b != 0
else
return gcd(b, a % b);
}
// lcm() method returns the LCM of a and b
static int lcm(int a, int b, int gcdValue)
{
return Math.abs(a * b) / gcdValue;
}
// Driver method
public static void main(String[] args) {
int a = 20, b = 30, gcdValue;
gcdValue = gcd(a, b);
// calling gcd() over
System.out.println("GCD = " + gcdValue);
// calling lcm() over integers 30 and 20
System.out.println("LCM = " + lcm(a, b, gcdValue));
}
}
GCD = 10
LCM = 60