More-of-the-input iterative algorithms extend a solution for a smaller input instance into a larger one. We will see in Chapter 9 that recursive algorithms do this too. The following is an amazing algorithm that does this. It finds the greatest common divisor (GCD) of two integers. For example, GCD(18, 12) = 6. It was first done by Euclid, an ancient Greek. Without the use of loop invariants, you would never be able to understand what the algorithm does; with their help, it is easy.
Specifications: An input instance consists of two positive integers, a and b. The output is GCD(a,b).
The Loop Invariant: Like many loop invariants, designing this one required creativity. The algorithm maintains two variables x and y whose values change with each iteration of the loop under the invariant that their GCD, GCD(x,y), does not change, but remains equal to the required output GCD(a, b).
Type of Loop Invariant: This is a strange loop invariant. The algorithm is more like recursion. A solution to a smaller instance of the problem gives the solution to the original.
Establishing the Loop Invariant: The easiest way of establishing the loop invariant that GCD(x, y) = GCD(a, b) is by setting x to a and y to b.
Measure of Progress: Progress is made by making x or y smaller.
Ending: We will exit when x or y is small enough that we can compute their GCD easily. By the loop invariant, this will be the required answer.