MATH-P5

The Chinese remainder theorem

Practice 5 of 7Number theory and counting12 tests

The problem

Return the smallest whole number x, 0 or more, with x % mods[i] == rems[i] for every position i. If no such number exists, return None. The moduli may share factors.

crt([2, 3], [3, 5])         # 8
crt([2, 3, 2], [3, 5, 7])   # 23
crt([1, 3], [4, 6])         # 9
crt([1, 2], [4, 6])         # None: odd and even
crt([], [])                 # 0

Limits

  • Up to 2,000 conditions. Each modulus is from 1 to about 10¹⁸ (a 1 followed by 18 zeros), and each remainder is from 0 to its modulus minus 1. The answer can have thousands of digits; Python’s whole numbers hold it exactly.
  • pow(a, -1, m) and math.gcd are allowed. pow(a, -1, m) raises ValueError when a and m share a factor, so divide by the gcd first.

Builds on MATH-5 Modular inverse.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Sunzi's problemNot run
3No rulesNot run
4Moduli with a common factorNot run
5Rules that disagreeNot run
6Modulus 1Not run
7The same modulus twiceNot run
8One modulus divides anotherNot run
9Five rulesNot run
10Two moduli near 10¹⁸Not run
112,000 rulesNot run
122,000 rules, one wrongNot run