Let
All the solutions of this system are congruent modulo
nrich’s article on the chinese remainder
illustrates the system of equations with a coordinate system in
Example: Represent the number
The statement above is equivalent to
We can see that
What we want to do is the opposite, that is find the number whose representation in the coordinate system defined by the integers that belong to the set of integers
What we can do is express these conditions as a sum of scaled unit vectors that belong to each of axis of the coordinate systems, this means that a point
If we represent each point as
Let’s take the first term of the sum,
From the system of equations above we can see that
Given the fact that
Finally we have to plug these values into the equation
/**
* Computes the value of `x` for the linear congruent system of equations
*
* x ≡ a_1 (mod p_1)
* x ≡ a_2 (mod p_2)
* |
* x ≡ a_n (mod p_n)
*
* All the solutions are given by the expression `x + k · p_1p_2...p_n`
* where `k` is an integer
*
* @param {vector<int>} a
* @param {vector<int>} p
* @return {int} A solution for the system if it exists
*/
int chinese_remainder(vector<int> &a, vector<int> &p) {
int x = 0;
int product = 1;
for (int i = 0; i < p.size(); i += 1) {
product *= p[i];
}
for (int i = 0; i < a.size(); i += 1) {
int k = product / p[i];
x += a[i] * modular_multiplicative_inverse(k, p[i]) * k;
x %= product;
}
return x;
}