We consider how gcd (m, n) may evaluate, recalling an illustrative trace:
We now argue for termination. We note that the second argument to gcd strictly decreases in every recursive call:
- If m<n, then
gcd (m, n) will reduce to gcd (n, m): this is because the quo (m, n) reduces to 0 and rem (m, n) reduces to m.
- If m \geq n, then either
gcd (m, n) returns n or it reduces to something equivalent to gcd (n, rem (m, n)). The value of rem (m, n) is strictly less than n.
Because the entire algorithm takes is defined using operations that are defined on the natural numbers, the arguments never become negative. For this reason, we conclude that the computation must eventually terminate.
Now we wish to argue that when gcd (m, n) does terminate, it does so with the actual greatest common divisor of m and n. By our termination argument, we have a finite trace of recursive calls leading to a return value:
\mathtt {gcd}{\mathopen {}\left (m,n\right )\mathclose {}}\leadsto \mathtt {gcd}{\mathopen {}\left (i_0,j_0\right )\mathclose {}}\leadsto \mathtt {gcd}{\mathopen {}\left (i_1,j_1\right )\mathclose {}}\leadsto \cdots \leadsto \mathtt {return}~v
Let q and r be the quotient and remainder respectively of m and n, so that r<n and m = q\cdot n + r. We will proceed by induction on the trace (I know that we haven’t taught you induction yet; bear with me).
- If the trace returns right away, then that was because the remainder of m and n was 0, so n\mid m and therefore n is the greatest common divisor of m and n, and the return value was n, so we are done.
- Otherwise, we may assume by induction that
gcd (i_0, j_0) does return the greatest common divisor of i_0 and j_0, and we need to show that this is also the greatest common divisor of m and n. In this case, we know that the remainder of m and n was some positive integer r, and that i_0 = n and j_0=r. But now we recall our characterisation of common divisor sets, namely that the common divisors of m and n are the same as the common divisors of n and the remainder of m and n, so we have the following equation:
\mathsf {CD}{\mathopen {}\left (m,n\right )\mathclose {}} = \mathsf {CD}{\mathopen {}\left (n,\operatorname {rem}{\mathopen {}\left (m,n\right )\mathclose {}}\right )\mathclose {}} = \mathsf {D}{\mathopen {}\left (\gcd {\mathopen {}\left (n,\operatorname {rem}{\mathopen {}\left (m,n\right )\mathclose {}}\right )\mathclose {}}\right )\mathclose {}}
Then by Observation [01E7], we conclude that the greatest common divisor of m and n is the greatest common divisor of n and \operatorname {rem}{\mathopen {}\left (m,n\right )\mathclose {}}, so we are done.