On this page
Interactive
Replace (a, b) by (b, a mod b) until the remainder is zero
Division trace
| # | a | b | q | r |
|---|
Press Divide to run the first division.
a = q·b + r, 0 ≤ r < b · gcd(a, b) = gcd(b, r)
Computing a greatest common divisor by listing all divisors becomes slow as the inputs grow. The Euclidean algorithm replaces a pair by a smaller pair with the same common divisors, until the answer is visible. This article uses the nonnegative convention .
Why the replacement works
Let be nonnegative integers with . Euclidean division gives unique integers with
Then
Indeed, any integer dividing both also divides , and any integer dividing both also divides . Thus the two pairs have exactly the same common divisors, so their greatest nonnegative common divisor is the same.
Trace and termination
For and , the successive divisions are
Each replacement preserves the gcd, so
Whenever the remainder is positive it is smaller than the preceding divisor. The nonnegative remainders therefore decrease strictly and must eventually reach zero. The last nonzero value is the gcd. In particular, for every nonnegative , including the conventional value .
For positive inputs, the number of divisions is : in the slowest case the remainders follow consecutive Fibonacci-sized values, so the smaller input decreases by a constant factor every two steps. This counts arithmetic steps, not the bit cost of operating on arbitrarily large integers.
Iterative C++ implementation
The function accepts only nonnegative int values representable by int. This precondition avoids relying on C++ remainder behavior for negative inputs; it returns the nonnegative gcd and gives gcd(0, 0) == 0.
int gcd(int a, int b) {
// Precondition: a >= 0 and b >= 0.
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
At each pass, remainder is the in , and the pair becomes without changing its gcd. When b is zero, a is the result.