Solution: Euclidean Algorithm

Learn the Euclidean algorithm for calculating the greatest common divisor in detail.

How does the Euclidean algorithm work?

The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger value of one of them is replaced by the difference between the two numbers.

Let’s look at an example:

The GCD of 252252 and 105105 is 2121 (252=21×12252 = 21 \times 12 and 105=21×5105 = 21 \times 5). Now, 2121 is also the GCD of 105105 and 147147 (252105252 - 105). Replacing the number with the larger value (initially 252252) with the difference between them (initially 147147) results in the larger number being reduced to a smaller value. Repeatedly performing this reduction will result in successively smaller pairs of numbers that will eventually equate to each other. When this occurs, the final number is the GCD of the two original numbers we started with.

The slides below demonstrate a subtraction-based animation of the Euclidean algorithm. Assume that the initial rectangle has dimensions a=1071a = 1071 and b=462b = 462. Two yellow squares of size 462×462462 \times 462 are placed within it, leaving a 462×(1071462462=)147462 × (1071-462-462 = )147 rectangle. This rectangle is tiled with 147×147147×147 blue squares until a 21×14721×147 rectangle is left, which in turn is tiled with 21×2121×21 red squares, leaving no uncovered area. The smallest square size, 2121, is the GCD of 10711071 and 462462.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.