The Chinese remainder theorem (CRT) is a theorem which gives a unique solution to a simultaneous linear congruences with coprime moduli. In its basic form, the CRT will determine a number p that, when divided by some given divisors, leaves given remainders.
If m1,...,mk are pairwise coprime, i.e., gcd(mi,mj)=1 for i=j, then the following system
⎩⎨⎧x≡a1(modm1)x≡a2(modm2)...,x≡ak(modmk)
has exactly one solution in the sense of module M=Πi=1kmi for any a1,a2,...,ak∈Z.
We define Mi=M/mi and ti≡Mi−1(modmi), then the solution to this congruences is x≡∑i=1kaiMiti(modM). Note that x is unique modulo M.
longlongCRT(int k, longlong* a, longlong* m){
longlong M = 1, ans = 0;
for (int i = 1; i <= k; ++i)
M = M * m[i];
for (int i = 1; i <= k; ++i) {
longlong Mi = M / m[i], ti, _;
exgcd(Mi, m[i], ti, _); // get inverse: ti * Mi mod m[i] = 1
ans = (ans + a[i] * Mi % M * ti % M) % M;
}
return (ans % M + M) % M;
}