Chapter 11 Exercise 11.3 Question 1 Solution : How would the original gcd algorithm change if we computed the divisors of n by examining the numbers from n down to 1, in reverse order?
The loop now runs "for each j from n down to 1". The first divisor found is n itself and the last is 1, so the list is decreasing.
| Number | Divisors found in reverse order |
|---|---|
| 18 | [18, 9, 6, 3, 2, 1] |
| 375 | [375, 125, 75, 25, 15, 5, 3, 1] |
| 825 | [825, 275, 165, 75, 55, 33, 25, 15, 11, 5, 3, 1] |
Going through divisors-of-m in order and keeping those that are also in divisors-of-n, we get the common divisors of 375 and 825 as [75, 25, 15, 5, 3, 1].
The original last step reports the rightmost element. Now that is 1, which is wrong, because gcd(375, 825) = 75.
Change the last step to report the leftmost (first) element of common-divisors. Here that is 75, which is correct.
There is a bonus: since the first common divisor we meet is already the greatest, we can stop at the first one and need no list of common divisors at all.
Examining from n down to 1 gives decreasing lists, so the algorithm must report the leftmost common divisor (the first found) instead of the rightmost.
