Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Math

The Biggest Tile That Fits.

Don't memorize the Euclidean algorithm — see it as tiling. The greatest common divisor of two numbers is the side of the largest square that fills their rectangle with no gap. Peel off the biggest square that fits, tile the leftover strip, repeat. The last square that fits exactly is the GCD — and that is precisely the ancient rule gcd(a, b) = gcd(b, a mod b), older than algebra and still unbeaten.

gcd = largest tiling square · (a, b) → (b, a mod b) · stop at 0 · O(log n)
GCD

The largest number dividing both a and b — the biggest square tile that fills their rectangle.

KEY FACT

gcd(a, b) = gcd(b, a mod b) — removing whole squares never changes the answer.

REDUCE

Replace the pair (a, b) with (b, a mod b). The numbers shrink fast.

STOP AT ZERO

When the remainder hits 0, the other number is the GCD. gcd(x, 0) = x.

euclid.sim — gcd(48, 18) by tiling a 48×18 rectangle
Ready

A 48 × 18 rectangle. The GCD is the side of the biggest square that could tile it perfectly. Press Step: peel off the largest square that fits, then tile whatever strip is left over — until nothing remains.

gcd(a, b) = gcd(b, a mod b),   gcd(x, 0) = x
—
Remainder
?
GCD

Why removing squares is safe

Picture the two numbers as the sides of a rectangle, 48 by 18. Any square tile that fills it perfectly must have a side dividing both 48 and 18 — so the largest such tile is exactly the GCD. Now the trick: chop off as many 18 by 18 squares as fit along the long side. Two fit, using up 36, and a 12 by 18 strip is left. Crucially, a tile that fills the original rectangle also fills that strip, and vice versa — cutting off whole squares removes nothing that matters. So the problem shrinks to tiling a 12 by 18 rectangle, then 12 by 6, then 6 by 6, which tiles exactly. The final square has side 6: gcd(48, 18) = 6. In numbers, each peel is one a mod b.

01

The insight

Write a = q·b + r. Any common divisor of a and b also divides r = a − q·b, so gcd(a, b) = gcd(b, r).

02

Reduce

Replace (a, b) with (b, a mod b) — the larger value becomes the remainder.

03

Repeat

Remainders shrink at least by half every two steps, so only about log-many steps are needed.

04

Terminate

When b = 0, the other number is the GCD, because every number divides 0.

Time
O(log n)
Space
O(1)
Worst case
Fibonacci
Idea
gcd(b, a%b)

The algorithm is two lines of code and it never gets stuck: the remainder strictly decreases and is bounded below by zero, so it must terminate — fast. The slowest inputs are consecutive Fibonacci numbers, and even then Lamé's theorem caps the step count at roughly five times the digit count of the smaller number. This same reduction is the engine behind reducing fractions, the extended Euclidean algorithm for modular inverses, and the sieve-adjacent world of number theory. Simple idea, enormous reach.

Check yourself

1 · The Euclidean algorithm reduces gcd(a, b) to…

The modulo form does all the repeated subtractions at once: (a, b) becomes (b, a mod b), and the common divisors are unchanged.

2 · When does the algorithm stop, and what is the answer?

Once the remainder becomes 0, the other number divides it (everything divides 0), so that number is the GCD.

3 · What does the GCD mean geometrically?

A square tiles the rectangle with no gap only if its side divides both dimensions, so the biggest such square has side gcd(a, b).

The picture: four boxes to the answer

1071, 462462, 147147, 2121, 0 (a, b)(b, a mod b)(b, a mod b)b = 0, stop 1071 = 2 × 462 + 147462 = 3 × 147 + 21147 = 7 × 21 + 0every common divisor of 1071 and 462 divides each remainderso the divisor set never changes; the numbers just shrinklast non-zero remainder: 21
Euclid on 1071 and 462. Each arrow replaces (a, b) by (b, a mod b). The pair changes, the set of common divisors does not, and the second number reaches 0 after 3 divisions.

Worked example, step by step

Two inputs, run side by side so you can compare them: gcd(1071, 462), an ordinary pair, and gcd(34, 21), two consecutive Fibonacci numbers, which is the slowest case Euclid has. Each row writes the division a = q·b + r and then moves on with (b, r).

InputStep(a, b)DivisionRemainder r
1071, 46211071, 4621071 = 2·462 + 147147
1071, 4622462, 147462 = 3·147 + 2121
1071, 4623147, 21147 = 7·21 + 00
1071, 462stop21, 0b = 0gcd = 21
34, 21134, 2134 = 1·21 + 1313
34, 21221, 1321 = 1·13 + 88
34, 21313, 813 = 1·8 + 55
34, 2148, 58 = 1·5 + 33
34, 2155, 35 = 1·3 + 22
34, 2163, 23 = 1·2 + 11
34, 2172, 12 = 2·1 + 00
34, 21stop1, 0b = 0gcd = 1

The first input takes 3 divisions and ends at 21. Notice that 1071 and 462 are three and four digits wide but the numbers collapse fast: 1071 to 147 in two steps. The second input is the stress test. Every quotient is 1, so each step removes only the smallest possible amount, and it still needs 7 divisions to reduce 34 and 21, always ending in (2, 1) then (1, 0). No pair of numbers up to 34 does worse, which is why Fibonacci numbers show up in the proof of the step bound. The answer for the first pair also gives the Bézout identity for free: running the same recursion backwards gives 21 = 1071 × (−3) + 462 × 7.

Complexity and trade-offs

CaseTimeSpaceWhy
Euclid with %O(log min(a, b))O(1) iterativeRemainders at least halve every two steps. gcd(832,040, 514,229) takes 28 divisions; gcd(1071, 462) takes 3.
Euclid by repeated subtractionO(max(a, b)) worstO(1)gcd(1,000,000, 1) takes 999,999 subtractions where the modulo form takes 1 division.
Trial division from min(a, b) downwardO(min(a, b))O(1)For the coprime pair 832,040, 514,229 it tests 514,229 candidates before reaching 1.
Binary GCD (shifts and subtraction)O(log a + log b) bit operationsO(1)Avoids the hardware divide; wins on some CPUs and big-integer libraries, loses on others.
Extended EuclidO(log min(a, b))O(1) iterativeSame loop carrying two extra coefficients, so Bézout and modular inverses cost the same as the plain gcd.

The 514,229-versus-28 gap is the whole reason the algorithm is still taught after two thousand years: the work is proportional to the number of digits, not to the size of the numbers. The trade-off is that the modulo is a division, and division is the slow instruction on many processors, which is the only reason binary GCD exists. For arbitrary-precision integers the cost per step also grows with digit count, so the total is roughly quadratic in the digit length with schoolbook arithmetic.

Common mistakes

  • Letting the sign leak through

    In languages where % keeps the sign of the dividend (C, Java, JavaScript), the textbook loop returns negative answers: gcd(−12, 0) returns −12, and gcd(−12, 18) returns 6, which only happens to be right in magnitude. Take abs of both inputs first, or of the result.

  • Multiplying before dividing in lcm

    lcm = a * b / gcd overflows long before the answer does. In JavaScript doubles, lcm(94906267, 94906265) computes 9007199326062756, but the exact value is 9007199326062755. Divide first: a / gcd * b.

  • Forgetting that gcd(0, 0) is 0

    The loop returns 0 for gcd(0, 0), so a / gcd * b then divides by zero. Guard lcm: if either input is 0, return 0 before dividing. The same applies to reducing the fraction 0/0.

  • Using subtraction with a zero

    The subtractive version, while a != b, never terminates on gcd(5, 0): it subtracts 0 forever (still looping after 1000 iterations, when the test harness cut it off). Use the modulo version, or handle zeros before the loop.

  • Dividing by b before checking it

    A recursion written as gcd(a, b) = gcd(b, a % b) must test b == 0 first. Testing a == 0 instead crashes on gcd(5, 0) in Python with ZeroDivisionError on the very first %.

Where this shows up

  • Reducing fractions

    Dividing numerator and denominator by their gcd gives lowest terms: 1071/462 becomes 51/22. Rational-number types in standard libraries do this on every operation.

  • Modular inverses and RSA-style arithmetic

    The extended form solves a·x ≡ 1 (mod m). The inverse of 17 modulo 3120 is 2753, because 17 × 2753 leaves remainder 1 on division by 3120. The same routine is used to derive decryption exponents and to divide in modular fields.

  • Periodic schedules

    Two jobs that repeat every 12 and every 18 seconds line up every lcm(12, 18) = 36 seconds. Any problem about gears, tiling, repeating patterns or synchronising cycles reduces to gcd and lcm.

  • Interviews and number theory

    Counting lattice points on a line segment, checking whether a water-jug target is reachable, and simplifying a slope as a pair of integers are all one gcd call. The standard libraries ship it (math.gcd in Python, std::gcd in C++17).

SOLVE IT YOURSELF

Solve it: gcd and lcm

Two thousand years old and still the fastest way to do it. Write it in Python or TypeScript, running for real in your browser.

YOUR TASK

Implement gcd(a, b) using the Euclidean algorithm, and lcm(a, b) on top of it. Handle zero and negative inputs: gcd(0, 5) is 5, gcd(-12, 18) is 6, and lcm of anything with 0 is 0.

HINTS — 5 IDEAS
  1. The insight: any common divisor of a and b also divides a % b — so the problem shrinks without losing the answer.
  2. Loop while b is non-zero: a, b = b, a % b. When b hits 0, a is the gcd.
  3. Take absolute values first — a gcd is conventionally non-negative.
  4. For lcm, use abs(a * b) // gcd(a, b), but divide before multiplying if you fear overflow in a fixed-width language.
  5. Guard lcm against zero explicitly, or you divide by a gcd of 0.
CPython · WebAssembly

Questions

Why is it so fast?

Every two iterations the larger number drops by at least half, so the values shrink geometrically — O(log min(a, b)) steps. The worst case is consecutive Fibonacci numbers; Lamé's theorem bounds the steps at about five times the digit count of the smaller input.

Subtraction version vs modulo version?

The original Euclid repeatedly subtracts the smaller number from the larger until they match. The modulo version collapses all those subtractions into one a mod b, which is dramatically faster when the two numbers differ a lot in size. Same GCD, better speed.

What is the extended Euclidean algorithm?

A version that also returns integers x and y with a·x + b·y = gcd(a, b). Those coefficients give modular inverses, which underpin RSA and other cryptography, so the humble GCD reaches surprisingly far.

Peel a square, tile the rest, repeat.

The GCD is the biggest tile that fills the rectangle — and finding it is just gcd(a, b) = gcd(b, a mod b) until nothing is left.

Finished this one? 0 / 99 Algorithms done
NextExtended Euclidean & CRT: gcd, and a Bonus Next on the “Number theory, in order” ladder · rung 2 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms