Solution: Euclidean Algorithm
Learn the Euclidean algorithm for calculating the greatest common divisor in detail.
We'll cover the following
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 and is ( and ). Now, is also the GCD of and (). Replacing the number with the larger value (initially ) with the difference between them (initially ) 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 and . Two yellow squares of size are placed within it, leaving a rectangle. This rectangle is tiled with blue squares until a rectangle is left, which in turn is tiled with red squares, leaving no uncovered area. The smallest square size, , is the GCD of and .
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.