目录
1. GCD
整数a和b的最大公约数是能同时整除a和b的最大整数,记为gcd(a, b)
1.1 性质
GCD有关的题目一般会考核GCD的性质。
(1)gcd(a, b) = gcd(a, a+b) = gcd(a, k·a+b)
(2)gcd(ka, kb) = k·gcd(a, b)
(3)多个整数的最大公约数:gcd(a, b, c) = gcd(gcd(a, b), c)
(4)若gcd(a, b) = d,则gcd(a/d, b/d) = 1,即a/d与b/d互素
(5)gcd(a+cb, b) = gcd(a, b)
1.2 代码实现
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
System.out.println(gcd(45, 9)); // 9
System.out.println(gcd(0, 42)); // 42
System.out.println(gcd(42, 0)); // 42
System.out.println(gcd(0, 0)); // 0
System.out.println(gcd(20, 15)); // 5
System.out.println(gcd(-20, 15)); // -5
System.out.println(gcd(20, -15)); // 5
System.out.println(gcd(-20, -15)); // -5
System.out.println(gcd(new BigInteger("98938441343232"), new BigInteger("33422"))); // 2
}
public static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static BigInteger gcd(BigInteger a, BigInteger b) {
return a.gcd(b);
}
}

最低0.47元/天 解锁文章
1352

被折叠的 条评论
为什么被折叠?



