Skip to content
StackDecode
Number theory & mathAnimated

Extended Euclidean Algorithm

Finds x, y with ax + by = gcd(a, b).

Time

O(log min(a, b))

Extra space

O(1)

Use it for

Modular inverses.

How it works

  1. Run the Euclidean algorithm, but also track coefficients x, y such that a·x + b·y equals the current remainder.
  2. Start with (a, 1, 0) and (b, 0, 1): each row satisfies "value = a·x + b·y".
  3. Each step subtracts q times the previous row from the one before it.
  4. When the remainder hits 0, the row before it gives the GCD and the coefficients (Bézout’s identity). If gcd = 1, x is the modular inverse of a mod b.

Watch it run

Loading animation…