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 Theory

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.

How Extended Euclid Works

  1. If b is 0, return (a, 1, 0) — the gcd is a, with x=1, y=0.
  2. Otherwise, recursively compute (g, x₁, y₁) = extendedGCD(b, a mod b).
  3. Back-substitute: x = y₁, and y = x₁ − ⌊a/b⌋ · y₁.
  4. 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 ✓

Number Theory: Extended EuclidO(log min(a,b))
Find x, y with a·x + b·y = gcd(a, b) — Bezout coefficients for modular inverses.
30
0
20
1
Step 1 / 7
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Extended Euclid: find x, y with 30·x + 20·y = gcd(30, 20).
Python · Number Theory in Code
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) * y1

Behind 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

BestO(log min(a,b))
AverageO(log min(a,b))
WorstO(log min(a,b))
SpaceO(log min(a,b)) — recursion / back-substitution stack

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.