Mental model
The greatest common divisor of a and b is the largest number that divides both. Trying every candidate from min(a, b) downwards takes up to min(a, b) steps, which is about a million for six-digit inputs. Euclid's algorithm needs at most a few dozen, because each step replaces the pair by a much smaller pair with exactly the same common divisors.
A picture helps: to tile a 1071 × 462 wall with the largest equal squares, cut off as many 462 × 462 squares as fit (two), leaving a 462 × 147 strip; tile that with 147-squares (three fit), leaving 147 × 21; 21-squares fill it exactly. The answer is 21. The lab's Tiles preset runs these numbers.
The algorithm
gcd(a, b): # a, b >= 0
while b != 0:
(a, b) = (b, a mod b)
return a
Every step writes a = q · b + r with 0 ≤ r < b. The lab shows each step as a row a = q · b + r,
with arrows for how b and r move one place left into the next row.
Why the step is correct
Let d divide both a and b. Then d divides r = a − q · b. Conversely, if d divides b and r, it divides a = q · b + r. So the pairs (a, b) and (b, r) have the same set of common divisors, and therefore the same greatest one. When b reaches 0 the answer is a, because every number divides 0.
If a < b, the first step has q = 0 and r = a, so it just swaps the two numbers. No special case is needed.
How many steps?
Look at two consecutive steps. If b ≤ a/2, then r < b ≤ a/2. If b > a/2, then q = 1 and r = a − b < a/2. Either way, after two steps the first number has at least halved, so the loop runs at most about 2 log₂(min(a, b)) times: O(log min(a, b)) iterations.
The worst case is when every quotient is 1, so the numbers shrink as slowly as possible. Running the algorithm backwards with all quotients equal to 1 produces the Fibonacci numbers: gcd(F(k+1), F(k)) takes k − 1 steps (Lamé's theorem, 1844). The Fibonacci preset uses 832,040 and 514,229 (F₃₀ and F₂₉): 28 steps, the most any pair below a million needs.
Each step is one division, so on fixed-size integers the total time is O(log min(a, b)). For numbers with thousands of digits each division costs more, and libraries switch to binary or Lehmer variants.
The least common multiple
lcm(a, b) is the smallest positive number both divide. Since gcd · lcm = a · b for positive a, b:
lcm(a, b) = 0 if a == 0 or b == 0
= (a / gcd(a, b)) * b
Divide first. a · b can overflow a 64-bit integer even when the lcm fits: lcm(999983, 999979)
is about 10¹², fine, but for numbers near 2⁶³ the product overflows long before the division. The
division a / gcd(a, b) is always exact. Even so, the lcm itself can exceed the type, so the
listings check: C# uses checked, Java Math.multiplyExact, C++ __builtin_mul_overflow (signed
overflow would be undefined behaviour), and Python needs nothing.
Zero, negatives and conventions
- gcd(a, 0) = a and gcd(0, 0) = 0 by convention (every number divides 0, so there is no largest common divisor of 0 and 0; 0 is the value that keeps the identities working).
- lcm(a, 0) = 0.
- For negative inputs, mathematicians take gcd(a, b) = gcd(|a|, |b|). The listings reject negative
numbers instead, because
%behaves differently across languages: in C#, Java and C++ the remainder takes the sign of the dividend (−7 % 3 = −1), in Python it takes the sign of the divisor (−7 % 3 = 2). Take absolute values first, and beware that |MinValue| does not fit in the type.
Related: fast exponentiation
Euclid's algorithm and binary exponentiation share the same idea, shrinking the problem
geometrically to get logarithmic step counts. Exponentiation by squaring, power(b, e) in O(log e)
multiplications, is covered with a visualizer in
Recursion and the call stack.
Combined with mod after each multiplication it gives modular exponentiation, the core of RSA and
of hashing schemes.
Built-ins
| Language | gcd | lcm | Notes |
|---|---|---|---|
| C# | BigInteger.GreatestCommonDivisor |
none | no int/long gcd in the base library; write the loop |
| Java | BigInteger.gcd |
none | BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)) for longs |
| Python | math.gcd(*ints) (3.9+ accepts many) |
math.lcm(*ints) (3.9+) |
unbounded ints, negatives allowed (result is non-negative) |
| C++ | std::gcd (C++17, <numeric>) |
std::lcm |
std::lcm is undefined if the result does not fit; it does not report overflow |
The teaching implementation
Gcd / gcd and Lcm / lcm share one source file with the sieve in each language. Each language
reads one shared fixture (zeros, equal numbers, a divisor pair, coprime numbers, the Fibonacci worst
case, an lcm near 10¹²) and compares 3,000 random pairs with its built-in gcd (BigInteger,
math.gcd, std::gcd); C# and Python also compare the first 300 with a brute-force divisor search,
and C#, Java and C++ check that an lcm overflow is reported instead of wrapping.
Common mistakes
- Multiplying before dividing in the lcm.
- Assuming
%is non-negative for negative inputs in C#, Java or C++. - Recursing without a base case for b = 0, or swapping the arguments the wrong way:
gcd(b, a % b), notgcd(a % b, b). - Using the gcd of floating-point numbers:
%on doubles accumulates rounding error; work with integers (scale decimals first).
Edge cases
- One argument divides the other: one step, gcd is the smaller number.
- a = b: one step (a mod a = 0).
- a < b: one extra step that swaps them.
- 1 and anything: gcd 1, lcm the other number.
Worked practice
1. Trace gcd(252, 105).
Answer
252 = 2 · 105 + 42; 105 = 2 · 42 + 21; 42 = 2 · 21 + 0. gcd = 21, after three steps. lcm = 252 / 21 · 105 = 1,260.
2. Why does gcd(a, b) never need more than about 2 log₂ b steps?
Answer
Over any two consecutive steps the larger number at least halves (either b ≤ a/2, or q = 1 and the remainder a − b < a/2), so after 2k steps it is at most min(a, b) / 2ᵏ.
3. Two buses leave the station every 12 and 18 minutes. When do they next leave together?
Answer
After lcm(12, 18) = 12 / gcd(12, 18) · 18 = 12 / 6 · 18 = 36 minutes.
Summary
- gcd(a, b) = gcd(b, a mod b) because both pairs have the same common divisors; stop when b = 0.
- O(log min(a, b)) steps; consecutive Fibonacci numbers are the worst case.
- lcm = a / gcd · b, dividing first, with an overflow check in fixed-width languages.
- Watch
%with negatives; C++17 and Python ship gcd and lcm, C# and Java only forBigInteger.