/**
* 中国剩余定理
*/
public class ChineseRemainderTheorem {
// 扩展欧几里得算法,返回gcd(a, b)以及x, y使得ax + by = gcd(a, b)
public static int extendedGCD(int a, int b, int[] xy) {
if (b == 0) {
xy[0] = 1;
xy[1] = 0;
return a;
}
int gcd = extendedGCD(b, a % b, xy);
int temp = xy[0];
xy[0] = xy[1];
xy[1] = temp - (a / b) * xy[1];
return gcd;
}
// 使用中国剩余定理求解同余方程组
public static int chineseRemainder(int[] n, int[] a) {
int prod = 1; // 模数乘积
for (int i = 0; i < n.length; i++) {
prod *= n[i];
}
int result = 0;
for (int i = 0; i < n.length; i++) {
int p = prod / n[i];
int[] xy = new int[2];
extendedGCD(p, n[i], xy); // 求解p * x ≡ 1 (mod n[i])
int inverse = xy[0];
result += a[i] * inverse * p;
}
return (result % prod + prod) % prod; // 保证结果为正数
}
public static void main(String[] args) {
// 定义模数数组和余数数组
int[] n = {3, 5, 7};
int[] a = {2, 3, 2};
// 使用中国剩余定理求解
int result = chineseRemainder(n, a);
System.out.println("结果是: " + result);
}
}