Skip to content

Instantly share code, notes, and snippets.

@corehello
Last active April 19, 2022 16:24
Show Gist options
  • Save corehello/c173ff5b3be5e79642234a7b57c4a239 to your computer and use it in GitHub Desktop.
Save corehello/c173ff5b3be5e79642234a7b57c4a239 to your computer and use it in GitHub Desktop.
from operator import mul, add
from functools import reduce
def chinese_remainder_theorem(tuple):
transpose = list(zip(*tuple))
product = reduce(mul, transpose[0])
min_result = reduce(add, [
j * l *(l%i) for i,j in tuple for l in [reduce(mul, [k for k in transpose[0] if k != i])]
]) % product
print("The value is: %s + n * %s which n = 0..inf" % (min_result, product))
return min_result, product
@corehello
Copy link
Author

corehello commented Apr 10, 2022

Q: one number modulo 3 is 2, modulo 5 is 1, modulo 7 is 4, then what's the value of the number?

> print(chinese_remainder_theorem(((3,2),(5,1),(7,4))))
The value is: 11 + n * 105 which n = 0..inf
(11, 105)

@qiwihui
Copy link

qiwihui commented Apr 19, 2022

cool~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment