Extended Euclidean Algorithm
- •
What it is
- •
n extension of Euclid's algorithm that, alongside , also returns integers satisfying Bézout's identity .
- •
- •
When to apply
- •
Whenever you need a modular inverse under a modulus that isn't necessarily prime, or need to combine two moduli/coefficients into a single linear relationship (e.g. building blocks for CRT or RSA key generation).
- •
- •
Symbols and assumptions
- •
are integers; is their greatest common divisor. Bézout coefficients satisfy . An inverse of modulo exists exactly when .
- •
- •
Math — step by step
- •
- Divide with remainder: . A number divides both exactly when it divides both , because . Therefore replacing by preserves the gcd.
- •
- Repeat until the remainder is zero. The final nonzero remainder is the gcd. Each division also writes one remainder as an integer combination of the previous two.
- •
- Substitute those remainder equations backward until the gcd is written using the original . Reduce modulo : the term vanishes, leaving . Thus is the inverse.
- •
- •
- •
Python
- •
def extended_gcd(a, b): if b == 0: return a, 1, 0 g, x1, y1 = extended_gcd(b, a % b) return g, y1, x1 - (a // b) * y1
- •
- •
SageMath
- •
g, u, v = xgcd(26513, 32321) # (1, 10245, -8404)
- •
- •
- •