Created
March 16, 2025 10:30
-
-
Save monperrus/f84480b0b2924cc5fba0a0c6eaf4ba39 to your computer and use it in GitHub Desktop.
implement the chinese remainder theorem in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def extended_euclidean(a, b): | |
| if a == 0: | |
| return b, 0, 1 | |
| else: | |
| g, x, y = extended_euclidean(b % a, a) | |
| return g, y - (b // a) * x, x | |
| def chinese_remainder(n, a): | |
| sum = 0 | |
| prod = 1 | |
| for ni in n: | |
| prod *= ni | |
| for ni, ai in zip(n, a): | |
| p = prod // ni | |
| g, x, y = extended_euclidean(p, ni) | |
| if g != 1: | |
| raise Exception('Moduli are not coprime') | |
| else: | |
| sum += ai * y * p | |
| return sum % prod | |
| n = [3, 5, 7] | |
| a = [2, 3, 2] | |
| print(chinese_remainder(n, a)) # Output: 23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment