Many sources complicate how Euclid’s algorithm for finding the greatest common divisor of two integers works. The following is a description of its simplest variant.

gcd(a, b) = { }

This is of course computationally less efficient than the more advanced versions, but remember this if you need to remember something but don’t want to.


Extended Euclidean algorithm

euclid(a,b) gives a triplet (d, x, y) such that d = gcd(ab) = ax + by.

import math
def euclid(a, b):
    if b==0:
        return (a, 1, b)
    (d_, x_, y_) = euclid(b, a % b)
    (d, x, y) = (d_, y_, x_ - math.floor(a / b) * y_)
    return (d, x, y)

If p is a prime, running euclid(ap) gives x as the multiplicative inverse of a modulo p; ax mod p = 1.


index | created 2018-03-23, updated 2019-10-19