You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.3 KiB

  1. # Chinese Remainder Theorem
  2. def crt(a_i, m_i, M):
  3. if len(a_i)!=len(m_i):
  4. raise Exception("error, a_i and m_i must be of the same length")
  5. x = 0
  6. for i in range(len(a_i)):
  7. M_i = M/m_i[i]
  8. y_i = Integer(mod(M_i^-1, m_i[i]))
  9. x = x + a_i[i] * M_i * y_i
  10. return mod(x, M)
  11. # gcd, using Binary Euclidean algorithm
  12. def gcd(a, b):
  13. g=1
  14. # random_elementove powers of two from the gcd
  15. while mod(a, 2)==0 and mod(b, 2)==0:
  16. a=a/2
  17. b=b/2
  18. g=2*g
  19. # at least one of a and b is now odd
  20. while a!=0:
  21. while mod(a, 2)==0:
  22. a=a/2
  23. while mod(b, 2)==0:
  24. b=b/2
  25. # now both a and b are odd
  26. if a>=b:
  27. a = (a-b)/2
  28. else:
  29. b = (b-a)/2
  30. return g*b
  31. # Extended Euclidean algorithm
  32. # Inputs: a, b
  33. # Outputs: r, x, y, such that r = gcd(a, b) = x*a + y*b
  34. def egcd(a, b):
  35. s=0
  36. s_=1
  37. t=1
  38. t_=0
  39. r=b
  40. r_=a
  41. while r!=0:
  42. q = r_ // r
  43. (r_,r) = (r,r_ - q*r)
  44. (s_,s) = (s,s_ - q*s)
  45. (t_,t) = (t,t_ - q*t)
  46. d = r_
  47. x = s_
  48. y = t_
  49. return d, x, y
  50. # Inverse modulo N, using the Extended Euclidean algorithm
  51. def inv_mod(a, N):
  52. g, x, y = egcd(a, N)
  53. if g != 1:
  54. raise Exception("inv_mod err, g!=1")
  55. return mod(x, N)