fork download
  1. from functools import reduce
  2.  
  3. def chinese_remainder(n, a):
  4. sum = 0
  5. prod = reduce(lambda a, b: a*b, n)
  6. for n_i, a_i in zip(n,a):
  7. p = prod/n_i
  8. sum += a_i * mul_inv(p, n_i) * p
  9. return sum % prod
  10.  
  11. def mul_inv(a, b):
  12. b0 = b
  13. x0, x1 = 0,1
  14. if b == 1:
  15. return 1
  16. while a > 1:
  17. q = a // b
  18. a , b = b, a%b
  19. x0, x1 = x1 -q*x0, x0
  20. if x1 < 0:
  21. x1 += b0
  22. return x1
  23.  
  24. a = [2,3,5]
  25. n = [5,11,17]
  26.  
  27.  
  28. print(chinese_remainder(n,a))
Success #stdin #stdout 0.04s 10048KB
stdin
Standard input is empty
stdout
872.0