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)andmath.gcdare allowed.pow(a, -1, m)raisesValueErrorwhen 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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
12 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Sunzi's problem | Not run | |
| 3 | No rules | Not run | |
| 4 | Moduli with a common factor | Not run | |
| 5 | Rules that disagree | Not run | |
| 6 | Modulus 1 | Not run | |
| 7 | The same modulus twice | Not run | |
| 8 | One modulus divides another | Not run | |
| 9 | Five rules | Not run | |
| 10 | Two moduli near 10¹⁸ | Not run | |
| 11 | 2,000 rules | Not run | |
| 12 | 2,000 rules, one wrong | Not run |