Chinese Remainder Theorem Solver - Problem

Given a system of simultaneous congruences, solve for the unique solution modulo the product of all moduli using the Chinese Remainder Theorem.

The system of congruences is given as:

  • x ≡ a₁ (mod m₁)
  • x ≡ a₂ (mod m₂)
  • ...
  • x ≡ aₖ (mod mₖ)

Where all moduli m₁, m₂, ..., mₖ are pairwise coprime (their greatest common divisor is 1).

Return the unique solution x such that 0 ≤ x < M, where M = m₁ × m₂ × ... × mₖ.

Input & Output

Example 1 — Basic Three Congruences
$ Input: remainders = [2,3,2], moduli = [3,5,7]
Output: 23
💡 Note: System: x ≡ 2 (mod 3), x ≡ 3 (mod 5), x ≡ 2 (mod 7). Check: 23%3=2✓, 23%5=3✓, 23%7=2✓
Example 2 — Two Congruences
$ Input: remainders = [1,4], moduli = [2,5]
Output: 9
💡 Note: System: x ≡ 1 (mod 2), x ≡ 4 (mod 5). Check: 9%2=1✓, 9%5=4✓. Range is 0 to 9.
Example 3 — Larger Moduli
$ Input: remainders = [3,5,7], moduli = [4,9,11]
Output: 139
💡 Note: System: x ≡ 3 (mod 4), x ≡ 5 (mod 9), x ≡ 7 (mod 11). Solution x=139 within range [0, 395]

Constraints

  • 1 ≤ remainders.length = moduli.length ≤ 10
  • 2 ≤ moduli[i] ≤ 100
  • 0 ≤ remainders[i] < moduli[i]
  • All moduli are pairwise coprime (gcd(mᵢ, mⱼ) = 1 for i ≠ j)

Visualization

Tap to expand
Chinese Remainder Theorem SolverINPUT: System of Congruencesx ≡ 2 (mod 3)x ≡ 3 (mod 5)x ≡ 2 (mod 7)remainders = [2,3,2]moduli = [3,5,7]All moduli pairwise coprimeALGORITHM: CRT Formula1Calculate M = 3×5×7 = 1052Partial products:M₁=35, M₂=21, M₃=153Find modular inverses:y₁=2, y₂=1, y₃=14Sum: 2×35×2 + 3×21×1+ 2×15×1 = 233Result: 233 mod 105 = 23RESULT: Unique Solutionx = 23Solution FoundVerification:23 % 3 = 2 ✓23 % 5 = 3 ✓23 % 7 = 2 ✓Range: 0 ≤ x < 105Key Insight:The Chinese Remainder Theorem provides a direct mathematical formula to findthe unique solution without testing every possibility, using modular arithmetic.TutorialsPoint - Chinese Remainder Theorem Solver | CRT Formula Approach
Asked in
Google 15 Microsoft 12 Facebook 8 Amazon 6
12.5K Views
Medium Frequency
~35 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen