Algorithm Implementation/Mathematics/Extended Euclidean algorithm
From Wikibooks, open books for an open world
Contents |
Python [edit]
Both functions take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
Iterative algorithm [edit]
def egcd(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
Recursive algorithm [edit]
def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y)
Modular inverse [edit]
An application of extended GCD algorithm to finding modular inverses:
def modinv(a, m): g, x, y = egcd(a, m) if g != 1: return None # modular inverse does not exist else: return x % m