Skip to content
StackDecode
Number theory & mathAnimated

Chinese Remainder Theorem

Combine congruences with coprime moduli into one.

Time

O(k log m)

Extra space

O(1)

Use it for

Solving systems of modular equations.

How it works

  1. We want one number x that leaves remainder a1 when divided by m1, and a2 when divided by m2 (m1 and m2 must be coprime).
  2. Numbers satisfying the first condition are a1, a1 + m1, a1 + 2·m1, …
  3. Test each one against the second condition.
  4. The first match is the unique answer modulo m1·m2.

Watch it run

Loading animation…