Warning. Going from ideas to algorithms is not automatic… [01E1]
Instead of Idea [01DX], we might have just as well considered the following recursive characterisation of the greatest common divisor, where we put the remainder in the first parameter instead of the second:
\gcd {\mathopen {}\left (m,n\right )\mathclose {}} = \begin {cases} n & \text {if } n\mid m\\ \gcd {\mathopen {}\left (\operatorname {rem}{\mathopen {}\left (m,n\right )\mathclose {}},n\right )\mathclose {}} &\text {otherwise} \end {cases}This is correct because the greatest common divisor of two numbers does not depend on the order in which they are given. From here, we might have then been led to consider the following “algorithm” for computing the gcd:
let rec gcd' (m, n) = let (q, r) = divide (m, n) in if r = 0 then n else gcd' (r, n)
The above is valid OCaml code, but it will not compute the gcd. How is this possible? The issue is that it is does not terminate on all inputs, which we can easily illustrate by comparison with our prior example trace of Euclid’s algorithm:
\begin {aligned} \mathrm {gcd}'{\mathopen {}\left (13,34\right )\mathclose {}} &\leadsto \mathrm {gcd}'{\mathopen {}\left (13,34\right )\mathclose {}} \\ &\leadsto \mathrm {gcd}'{\mathopen {}\left (13,34\right )\mathclose {}} \\ &\leadsto \mathrm {gcd}'{\mathopen {}\left (13,34\right )\mathclose {}} \\ &\cdots \end {aligned}The problem is that the remainder \operatorname {rem}{\mathopen {}\left (13,34\right )\mathclose {}} is 13, so the parameter never gets smaller. The real Euclid’s algorithm essentially swaps the denominator in every recursive call, which causes the parameters to eventually decrease until termination. We will see a little later how to rigorously argue that the algorithm actually terminates.