Skip to content

Instantly share code, notes, and snippets.

@igorvanloo
Created May 22, 2022 13:53
Show Gist options
  • Save igorvanloo/e197aa4d83c970c3764d482650dff6fb to your computer and use it in GitHub Desktop.
Save igorvanloo/e197aa4d83c970c3764d482650dff6fb to your computer and use it in GitHub Desktop.
Chinese Remainder Theorem
def ChineseRemainderTheorem(a1, a2, n1, n2):
#x = a1 (mod n1)
#x = a2 (mod n2)
#We find p = n1^-1 (mod n2), q = n2^-1 (mod n1)
p ,q = pow(n1, -1, n2), pow(n2, -1, n1)
#The unique solution to this system is a1*q*n2 + a2*p*n1 % n1*n2
return (a1*q*n2+ a2*p*n1) % (n1*n2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment