Exercise · Volume 1 · 1.1-3
Exercise 1.1-3
not stated yet in Lean solution written
| Rating | 20 |
|---|---|
| Kind | K5, design an algorithm: give a method for a task, often with a cost bound from the written solution |
| Section | Section 1.1 of Volume 1. Companion chapter: Algorithms |
The task
Rewrite Euclid's algorithm so that no step only moves one variable to another, and give the new algorithm the name F.
The exact wording is in your copy of the book.
Hints
Open one hint at a time. Try the exercise again after each.
Hint 1
In Algorithm E, step E3 only renames: the old becomes and the remainder becomes .
Hint 2
Let the two variables swap their roles at each pass instead of moving their values. Divide by in one step and by in the next.
Solution
Show the solution
Algorithm F. Given two positive integers and , find their greatest common divisor.
- F1. [Reduce .] Set . If , stop. The answer is .
- F2. [Reduce .] Set . If , stop. The answer is . Otherwise go to F1.
The algorithm is correct. For positive integers and the pair has the same common divisors as , because for an integer , so a number that divides divides if and only if it divides . Hence and . At F1 both and are positive, since F2 reaches F1 only with and F1 is entered first with the given positive values. After F1 with the answer is . The same holds in F2.
The algorithm stops. After F1, , and after the next F2, . So the values taken by after F1 and by after F2 form a sequence of nonnegative integers, with because F1 takes a remainder modulo and because F2 takes a remainder modulo . A strictly decreasing sequence of nonnegative integers is finite, so the algorithm reaches a zero and stops.
Check
Take and . F1 gives since , and . F2 gives . F1 gives . F2 gives . F1 gives . F2 gives , so the answer is . The computation has 6 remainders and no move of a value.
Remarks
Algorithm F makes the same divisions as Algorithm E, so it has the same cost in divisions. It saves the two replacements of step E3 at each pass. The price is that the algorithm has two nearly equal steps, which is the usual price of unrolling a loop.
This solution is checked, and a person has not reviewed it yet. The source.
In Lean
not stated yet The exercise is not stated in Lean yet.
The status is computed from the Lean build. The node of the map.
Something is wrong? Report it.