import java.math.BigInteger;
public class Gcd {
public static void main(String[] args) {
System.out.println(gcdMax(13, 16));
System.out.println(lcm(208, 30));
}
// 欧几里得
public static int gcdMax(int a, int b) {
while (b > 0) {
int temp = a % b; // 直至余数 0
a = b;
b = temp;
}
return a;
}
// 递归
public static int gcdMaxFounction(int a, int b) {
return b == 0 ? a : gcdMaxFounction(b, a % b);
}
// 最小公倍数
public static int lcm(int a, int b) {
return (a * b) / gcdMax(a, b);
}
// 互质:最大公因数为 1 时
public static boolean gcdCoprime(int a, int b) {
return gcdMax(a, b) == 1 ? true : false;
}
// 当多个数求最小公倍数与最大公约数时,求法
// 按照这个逻辑,把两个不同的单个数直接得到最大公约数或最小公倍数结果时,再用结果去和第三个以上的数求最大公约数或最小公倍数
public static String gcdSuperLcm(long x) { // 1 ~ X 的最小公倍数求法, 1 ~ X 的最大公约数也是如此
BigInteger n = new BigInteger(x + "");
BigInteger one = new BigInteger("1");
BigInteger a = new BigInteger("1"); //初始最小公倍数1
for (BigInteger i = new BigInteger("1"); i.compareTo(n) <= 0; i = i.add(one)) {
a = a.multiply(i).divide(a.gcd(i));
}
return a.toString();
}
}
【蓝桥杯-GCD】模板示例
于 2023-05-06 15:34:57 首次发布