package com.company;
public class Main {
public static long exgcd(long a, long b, long[] u) {
if (b == 0) {
u[0] = 1;
u[1] = 0;
return a;
}
long g = exgcd(b, a % b, u);
long t = u[0]; u[0] = u[1]; u[1] = t;
u[1] -= a / b * u[0];
return g;
}
public static long inv(long a, long p) {
long[] u = {0, 0};
long x = 0, y = 0; exgcd(a, p, u);
return (u[0] % p + p) % p;
}
public static long CRT(int[] b, int[] p, int n) {
long mul = 1;
for (int i = 0; i < n; i++) {
mul *= p[i];
}
long res = 0;
for (int i = 0; i < n; i++) {
long t = mul / p[i];
res = (res + t * b[i] * inv(t, p[i])) % mul;
}
return res;
}
public static void main(String[] args) {
int[] p = {3, 5, 7};
int[] b = {2, 3, 2};
System.out.println(CRT(b, p, 3));
}
}
中国剩余定理 · Java版
最新推荐文章于 2022-09-19 23:15:45 发布