Skip to content
StackDecode
Number theory & mathAnimated

Euclidean Algorithm

gcd(a, b) = gcd(b, a mod b).

Time

O(log min(a, b))

Extra space

O(1)

Use it for

Greatest common divisor.

How it works

  1. The greatest common divisor does not change if you replace the larger number by its remainder after dividing by the smaller: gcd(a, b) = gcd(b, a mod b).
  2. Repeat until the remainder is 0.
  3. The last non-zero number is the GCD.
  4. It takes O(log min(a, b)) steps.

Watch it run

Loading animation…