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
- Run the Euclidean algorithm, but also track coefficients x, y such that a·x + b·y equals the current remainder.
- Start with (a, 1, 0) and (b, 0, 1): each row satisfies "value = a·x + b·y".
- Each step subtracts q times the previous row from the one before it.
- 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…