Let p1,p2,,pn be distinct numbers relatively prime, for any integers a1,a2,,an there’s an integer x such that

xa1(modp1)xa2(modp2)xan(modpn)

All the solutions of this system are congruent modulo p1p2pn

nrich’s article on the chinese remainder illustrates the system of equations with a coordinate system in n-dimensions, basically a number can represent a point in the coordinate system defined by the equation system and the point itself is a sum of unit vectors scaled by some amount

Example: Represent the number 17 in the coordinate system defined by the integers that belong to the set of integers Z/5, Z/7 and Z/11 (Z/n has n elements which are all the number in the range 0,1,,n1)

The statement above is equivalent to

17x2(mod5)17x3(mod7)17x6(mod11)

We can see that 17 is represented by the point (2,3,6)

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 Z/p1,Z/p2,,Z/pn results in the point (a1,a2,an)

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 (a1,a2,an) can be represented as

a1(1,0,0,,0)+a2(0,1,0,0,,0)++an(0,0,,0,1)=(a1,a2,,an)

If we represent each point as xi

(1)a1x1+a2x2++anxn=(a1,a2,,an)

Let’s take the first term of the sum, x1 is a number which must fulfill the following equivalences for each axis of the coordinate system

x11(modp1)x10(modp2)x10(modpn)

From the system of equations above we can see that x1p2p3pn which means that x1 is some multiple of the multiplication i.e. x1=p2p3pnx1

p2p3pnx11(modp1)

Given the fact that p2p3pn is relatively prime to p1 the product has a modular multiplicative inverse which can be found using the extended euclidean algorithm, in fact we have to solve n of this equations each having the form

p1p2pnpixi1(modpi)

Finally we have to plug these values into the equation (1)

/**
 * 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;
}