Let m and n be natural numbers with n positive. We first consider the circumstances under which the evaluation of \mathtt {divide}~m~n terminates. We have
\mathtt {divide}~m~n =
\mathtt {iterate\_division}~n~(0,m)
so
\mathsf {terminates}(\mathtt {divide}~m~n) \Longleftrightarrow
\mathsf {terminates}(\mathtt {iterate\_division}~n~(0,m))
\text {.}
\mathtt {iterate\_division}~n~(q,r) is defined so to terminate as soon as r gets small enough, and in each recursive call, r is getting smaller. Therefore, so long as n is positive, \mathtt {iterate\_division}~n~(q,r) is guaranteed to terminate and thus \mathtt {divide}~m~n is guaranteed to terminate.
We may now consider whether the values of \mathtt {divide}~m~n are pairs (q,r) such that r<n and m=qn+r. It is clear by inspection that the first condition holds. For the second, write P(q,r) for the statement m=qn+r. We will show that every call to \mathtt {iterate\_division} is with a pair satisfying P.
- The first call to \mathtt {iterate\_division} is with the pair (0,m), and we have m=0n+m.
-
In the recursive call, we assume that P(q,r) holds and must show that P(q+1,r-n) holds. We see below that this is equivalent to our assumption:
\begin {aligned}
P(q+1,r-n) &\Longleftrightarrow m = (q+1)n + (r-n)
\\
&\Longleftrightarrow m = qn+n + r - n
\\
&\Longleftrightarrow m = qn + r
\\
&\Longleftrightarrow P(q,r)
\end {aligned}
We have shown above that if \mathtt {divide}~m~n terminates, then it terminates with a pair satisfying the desired property. Combining this with our earlier argument that \mathtt {divide}~m~n alwyas terminates, we are finished.