Algorithms · Visualized
Number Theory: Extended Euclid
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
The extended Euclidean algorithm computes not just gcd(a,b), but also integer coefficients x and y such that a·x + b·y = gcd(a,b) (Bezout's identity) — the basis for computing modular multiplicative inverses in cryptography. Time: O(log min(a,b)) average, O(log min(a,b)) worst; space: O(log min(a,b)) — recursion / back-substitution stack.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Extended Euclidean Algorithm
Number TheoryThe extended Euclidean algorithm computes not just gcd(a,b), but also integer coefficients x and y such that a·x + b·y = gcd(a,b) (Bezout's identity) — the basis for computing modular multiplicative inverses in cryptography.
How Extended Euclid Works
- If b is 0, return (a, 1, 0) — the gcd is a, with x=1, y=0.
- Otherwise, recursively compute (g, x₁, y₁) = extendedGCD(b, a mod b).
- Back-substitute: x = y₁, and y = x₁ − ⌊a/b⌋ · y₁.
- Return (g, x, y), which satisfies a·x + b·y = g.
Extended Euclid Worked Example
Input: {a: 30, b: 20}
extendedGCD(30,20) → extendedGCD(20,10) → extendedGCD(10,0) returns (10,1,0). Back at (20,10): x=0, y=1−(20/10)·0=1 → (10,0,1). Back at (30,20): x=1, y=0−(30/20)·1=−1 → (10,1,−1). Check: 30·1 + 20·(−1) = 10 ✓
def ext_gcd(a, b):
if b == 0:
return a, 1, 0
g, x1, y1 = ext_gcd(b, a % b)
return g, y1, x1 - (a // b) * y1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Extended Euclid Time & Space Complexity
When to Use Extended Euclid
- Computing modular multiplicative inverses (needed in RSA cryptography).
- Solving linear Diophantine equations.
- Chinese Remainder Theorem implementations.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.