The Euclidean Algorithm

Given integers i and j we are looking for the largest integer d which divides both i and j. When an integer d divides integer i, that means that there is another integer s such that i=sd and if d divides integer j, there is another integer t such that j=td Then we can see that d divides the difference between i and j i - j = sd - td = (s - t)d In fact, for any multiple of j, for instance aj, d divides the difference between i and aj i - aj = sd - a(td) = (s - at) d This gives us a way of simplifying our task of actually finding d.

After accepting the input i, j, we arrange things so that i is larger than or equal to j. Then we use our integer division to select the integer a to make i - aj as small as possible, but not negative.

The d "hiding" inside of both i and j is also inside of j and i - aj because we showed that any d dividing i and j divides i - aj as well. We run the algorithm again by calling the procedure object inside the procedure object itself - we use recursion. Since i - aj is smaller than i, we re-instantiate the procedure object only a finite number of times: you just can't make integers smaller but positive forever!

So eventually, the first condition holds, the difference made is zero, and the value of d just pops out like magic - it is the j value at the level of recursion for which i-aj=0.