euclidean.py 850 B

1234567891011121314151617181920212223242526272829303132333435
  1. # a general Euclidean algorithm for any number type with
  2. # a divmod and a valuation abs() whose minimum value is zero
  3. def gcd(a, b):
  4. if abs(a) < abs(b):
  5. return gcd(b, a)
  6. while abs(b) > 0:
  7. _,r = divmod(a,b)
  8. a,b = b,r
  9. return a
  10. # extendedEuclideanAlgorithm: int, int -> int, int, int
  11. # input (a,b) and output three numbers x,y,d such that ax + by = d = gcd(a,b).
  12. # Works for any number type with a divmod and a valuation abs()
  13. # whose minimum value is zero
  14. def extendedEuclideanAlgorithm(a, b):
  15. if abs(b) > abs(a):
  16. (x,y,d) = extendedEuclideanAlgorithm(b, a)
  17. return (y,x,d)
  18. if abs(b) == 0:
  19. return (1, 0, a)
  20. x1, x2, y1, y2 = 0, 1, 1, 0
  21. while abs(b) > 0:
  22. q, r = divmod(a,b)
  23. x = x2 - q*x1
  24. y = y2 - q*y1
  25. a, b, x2, x1, y2, y1 = b, r, x1, x, y1, y
  26. return (x2, y2, a)