Chinese Remainder Theorem
Theorem
Given pairwise coprime positive integers and arbitrary integers , the system of simultaneous congruences
has a solution, and the solution is unique modulo .
The following is a general construction to find a solution to a system of congruences using the Chinese remainder theorem:
Compute .
For each , compute
For each , compute using Euclid's extended algorithm ( exists since are pairwise coprime).
The integer is a solution to the system of congruences, and is the unique solution modulo .
Code
int chineseRemainder(const vector<int> &n, const vector<int> &a) {
int k = n.size(), N = 1, x = 0;
for (int i = 0; i < k; ++i) N *= n[i];
for (int i = 0; i < k; ++i) {
int y = N / n[i];
maddi(x, mmul(a[i], mmul(y, minv(y, n[i]), N), N), N);
}
return x;
}
Use in Computation of Large Integers
Instead of large numbers, we can work with their remainders modulo several big prime numbers, if every number is less than product of all primes used.
In this form, it would be fast to sum and multiply large integers, but hard to compare. This is actually used to speed up computations.