Skip to content

Instantly share code, notes, and snippets.

@monperrus
Created March 16, 2025 10:30
Show Gist options
  • Select an option

  • Save monperrus/f84480b0b2924cc5fba0a0c6eaf4ba39 to your computer and use it in GitHub Desktop.

Select an option

Save monperrus/f84480b0b2924cc5fba0a0c6eaf4ba39 to your computer and use it in GitHub Desktop.
implement the chinese remainder theorem in python
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