[模板]中國剩餘定理
阿新 • • 發佈:2018-12-20
偷偷放個大佬的教學:中國剩餘定理 互質的情況
ll crt(int n, int *a, int *m){
ll M = 1, d, y, x = 0;
for(int i = 1; i <= n; i++) M*=m[i];
for(int i = 1; i <= n; i++) {
ll w = M/m[i];
d = exgcd(m[i], w, d, y);
x =(x+y*w*a[i])%M;
}
return (x+M)%M;
}
不互質的情況
ll ex_crt(int n, int *a, int *m){
if(n == 1 && a[1] == 0) return m[1];
ll M = m[1],A = a[1], t, d, x, y;
for(int i = 2; i <= n; i++){
d = exgcd(M,m[i],x,y);
if((a[i]-A)%d)return -1;
x *= (a[i]-A)/d;
t = m[i]/d; x = (x%t+t)%t;
A = M*x+A; M = M/d*m[i];
A%=M;
}
return (A+M)%M;
}