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
- 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).
- Repeat until the remainder is 0.
- The last non-zero number is the GCD.
- It takes O(log min(a, b)) steps.
Watch it run
Loading animation…