Algorithms

Euclidean algorithm

What is the largest square tile that can cover a 48 × 18 rectangle without cutting any tiles? The tile side must divide both dimensions. The Euclidean algorithm finds their greatest common divisor (GCD).

48 × 18

Divisions 0
Start with the longer side of the rectangle.

Video walkthrough

Squares show the remainder

Two 18 × 18 squares fit along the side of length 48. The remaining rectangle has sides 18 and 12. One 12 × 12 square fits inside it, leaving a 12 × 6 rectangle. Two 6 × 6 squares fill that remainder completely. The demo counts each division once, including the one with zero remainder. The final frame shows identical 6 × 6 tiles covering the entire floor.

Why the remainder is enough

If a = q × b + r, every common divisor of a and b divides r = a − q × b. Conversely, every common divisor of b and r divides q × b + r = a. Therefore GCD(a, b) = GCD(b, r). When r = 0, b divides both numbers in the current pair and is the largest number that does. By the chain of equalities it is also the GCD of the original dimensions.

How many divisions are needed

The remainder is always smaller than the divisor. Every two divisions reduce the current divisor by at least half. With positive integers a and b, the number of divisions is O(log(min(a, b) + 1)) when computing a remainder counts as one operation. The algorithm itself stores O(1) numbers. The demo also stores the history and square group coordinates so you can seek.

JavaScript implementation

Let a and b be nonnegative safe integers, at least one of them positive. If b is zero, the function returns a immediately. Both rectangle sides in the demo are positive. If a is smaller than b, the first division swaps them. In the diagram, each division starts with the longer side.

function gcd(a, b) {
    while (b !== 0) {
        const remainder = a % b;
        a = b;
        b = remainder;
    }
    return a;
}