Skip to content

Instantly share code, notes, and snippets.

@otms61
Created April 23, 2015 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otms61/7a1f7d81a90f5267d7cb to your computer and use it in GitHub Desktop.
Save otms61/7a1f7d81a90f5267d7cb to your computer and use it in GitHub Desktop.
math utils
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def egcd(a, b):
"""Return x and y such that
ax + by = gcd(a, b)"""
x, y, u, v = 0, 1, 1, 0
while a != 0:
q, r = b // a, b % a
m, n = x - u * q, y - v * q
b, a, x, y, u, v = a, r, u, v, m, n
return b, x, y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment