Volume C1 · Basic concepts · TAOCP Section 1.1
Algorithms
Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.
Read it next to Section 1.1 of the book. The nodes and the exercises of the section.
Algorithms and Euclid's algorithm
Overview
Section 1.1 of TAOCP does three things. It gives Algorithm 1.1E, Euclid's algorithm, which finds the greatest common divisor of two positive integers by repeated division. It lists the five properties that make a method an algorithm: finiteness, definiteness, input, output and effectiveness. Then it makes the idea exact: a computational method is a quadruple of states, inputs, outputs and a step function, and an algorithm is a computational method that stops on every input. It also asks how many steps Euclid's algorithm takes on the average, and it leaves the answer to Section 4.5.3. The section uses no earlier section of the book. The reader needs the division of integers with remainder, sets and functions (P1), and the idea of a state of a machine (P7).
The ideas
An algorithm is a list of exact steps. A cooking recipe tells a person what to do, but it leaves much to the cook: "add salt to taste" is not exact. An algorithm leaves nothing to the person or the machine that does it. Each step says exactly what to do with the values that are present, and the next step is always known. The book writes its algorithms as numbered steps with a letter, such as E1, E2, E3, and each step has a short name in brackets. C1 writes them in a pseudocode of its own (see the part Algorithms and programs).
Euclid's algorithm rests on one fact. If is the remainder of divided by , then and have the same common divisors as and . So , and the second pair is smaller. Try it by hand on and : the remainder of divided by is , and the remainder of divided by is . So , since divides . The algorithm repeats this one step until the remainder is .
Each claim about an algorithm needs a proof. An algorithm is correct when its output is the right answer for each input, and it is finite when it stops for each input. These are two different proofs. For Euclid's algorithm the first proof uses the fact above as an invariant, and the second uses the fact that the remainder gets smaller at each step. Section 1.2.1 turns both kinds of proof into a general method.
The count of steps is part of the study of an algorithm. A good algorithm is not only correct. It also uses few steps. The book counts how many times each step runs, first in the worst case and then on the average. For Euclid's algorithm the number of divisions is at most about , and the average for a fixed grows like a constant times .
A formal model makes "algorithm" a definition of mathematics. The five properties are in words. To prove a theorem about all algorithms, the book needs a definition in sets. It takes a set of states and a function from to . A run is the sequence , and it stops when it reaches an output state. This is the model of the Lean code of the project (TAOCP.CompMethod). The last part of the section adds effectiveness: when the states are strings of letters and each step replaces one string by another, each step is a thing that a person can do with pencil and paper.
The order of this chapter is the order of the book, but the proofs of correctness and of the bound on the number of steps are in C1 and not in the book. The book gives the idea of the correctness proof in words and leaves the details to Section 1.2.1 and to the exercises.
Definitions, results and proofs
Definition C1.1.1.1 (algorithm, the five properties, TAOCP Section 1.1). An algorithm is a finite list of rules that tells, for each input of a class of problems, which operations to do and in which order. It has these five properties:
- Finiteness. For each input, it stops after a finite number of steps.
- Definiteness. Each step says exactly what to do, with no doubt, in each case that can occur.
- Input. It takes zero or more inputs, from sets that are given in advance.
- Output. It gives one or more outputs, which have a stated relation to the inputs.
- Effectiveness. Each operation is so basic that a person can do it exactly, with pencil and paper, in a finite time.
Node: TABRV8A8VB · status: not stated yet
Explanation. The five properties separate an algorithm from a recipe, a plan or a program that runs for ever. Finiteness asks for a bound on the time for each input, not a bound that is the same for all inputs. Definiteness is about the text of the method: two people who follow it on the same input do the same operations. Effectiveness is about the size of each operation: "divide by " is effective for integers, but "find the largest prime factor of a number with digits" is not one step of a person with pencil and paper, even though it is definite. A method that has all the properties except finiteness is a computational method in the language of the book; an operating system and a program that waits for messages are of this kind. The book uses the word "algorithm" in this exact sense in all the later chapters, and each algorithm of the book comes with its inputs and its outputs.
Example. Euclid's algorithm has the five properties. Its inputs are two positive integers and . Its output is . Each step is a division with remainder, a test for zero or a copy of a value, so each step is definite and effective. It is finite because the remainder gets smaller at each step (Algorithm 1.1E below proves this). Now take the method "for in turn, add the divisors of that are less than , and stop when the sum is ". Each step is definite and effective, and the method has an input (none) and an output (the first odd number that is equal to the sum of its smaller divisors). But nobody knows if such a number exists, so nobody knows if the method stops. It is a computational method, and nobody can say today that it is an algorithm.
Definition C1.1.1.2 (computational method, TAOCP Section 1.1). A computational method is a quadruple , where is a set (the states), is the set of inputs, is the set of outputs, and is a function (the step) with for each . The method is an algorithm when the computation from each input stops, in the sense of the next definition.
Node: TA9FSNKHX3 · Lean: TAOCP.CompMethod, TAOCP.CompMethod.IsAlgorithm · status: not stated yet
Explanation. A state holds all that the method needs to know at one moment: the values of the variables and the step that comes next. The step function is one step of the method. The condition on says that an output state does not change, so "the computation has stopped" and "the computation is at an output" mean the same thing. This definition has the properties 1 to 4 of the five: the inputs are , the outputs are , each step is the value of a function (definiteness), and finiteness is the condition that each computation reaches . It does not have effectiveness, since can be any function, for example a function that knows the answer to an open problem. The definition of eq. 1.1(3) below adds effectiveness.
Example. Take , , , and let , for an even , and for an odd . Then leaves the one output state fixed, so is a computational method. From the input the states are , so the computation stops after steps with the output . Whether this method is an algorithm is the Collatz problem. It is open: nobody has proved that each input reaches , and nobody has found an input that does not.
Definition C1.1.1.3 (the computation from an input, TAOCP eq. 1.1(1)). Let be a computational method and let . The computation from is the sequence below. It stops in steps when is the least integer with , and then is its output. When no is in , the computation does not stop.
Node: TA98JDNJDF · Lean: TAOCP.CompMethod.run, TAOCP.CompMethod.Terminates, TAOCP.CompMethod.steps, TAOCP.CompMethod.output · status: not stated yet
Explanation. The sequence is the list of states that the method goes through. The number is the number of steps, and the output is the first state in . After that state the sequence does not change: if , then , and by induction for each . So it does not matter which state of in the sequence one calls "the output": all of them are the same state. This is the fact TAOCP.CompMethod.run_eq_of_le of the Lean code. The number of steps is the time of the computation, and Section 1.2.10 and all the analyses of the book count parts of it.
Example. In the method of the last example, the computation from is . The first state in is , so the computation stops in steps with the output .
Proof that the sequence stays at its output. Let . For the claim is true. If for some , then , so , because leaves each state of fixed. By induction on , for each .
Definition C1.1.1.4 (Euclid's algorithm as a computational method, TAOCP eq. 1.1(2)). Let be the set of the tuples , and of integers with and . Let be the set of the pairs , let be the set of the one-tuples , and let
Node: TA4VC7CXEV · Lean: TAOCP.S1_1.E.method (partial) · status: not stated yet
Explanation. This puts Algorithm 1.1E into the form of the definition above. A pair is the state before a division. A triple is the state after the division, before the test of . A one-tuple is the answer. The function maps into : the remainder is less than , and when the pair has two positive members. The book uses four kinds of tuples, with a step number as the last member of each long tuple. The form here joins the test and the copy into one step, so it has three kinds of tuples. The two forms make the same divisions in the same order. The Lean code TAOCP.S1_1.E.method uses a third form: a state is a step label and a store with the variables , , .
Example. From the input the computation is
It stops in steps with the output , and indeed : and .
Proof that this is a computational method that is an algorithm. The function leaves each fixed, so is a computational method. For the stop, give each state the weight , and . A step from goes to the weight . A step from goes to the weight when , and to the weight when . So the weight gets smaller at each step until the state is in . A sequence of nonnegative integers that gets smaller at each step has at most members, so the computation from each input reaches . That the output is is the correctness proof of Algorithm 1.1E below.
Definition C1.1.1.5 (an effective computational method on strings, TAOCP eq. 1.1(3)). Let be a finite set of letters, let be the set of strings of letters of , and let . A method on strings is given by rules: for each with , a rule has two strings and two integers with . Its states are the pairs with and . The inputs are the states , the outputs are the states , and
Node: TAF1HD6GRG · status: not stated yet
Explanation. At the rule , the method looks for the first place where the string occurs in . If there is none, it goes to the rule and does not change . If there is one, it puts in place of that first copy of and goes to the rule . Each step is a search and a replacement in a string, which a person can do with pencil and paper, so a method of this kind has the fifth property, effectiveness. These methods are the normal algorithms of A. A. Markov. They can compute each function that a Turing machine can compute, so by the thesis of Church and Turing (see the notes) the definition does not lose any algorithm: an algorithm in the sense of the book is a method of this kind that stops on every input.
Example. Let and , with one rule: , the empty string, and . The rule removes the first and comes back to itself. When no is left, it goes to the output state. From the input the computation is
so the output is the string after steps. In general the method removes all the letters , and a string with letters takes steps.
Proof that the example method is an algorithm. Let be the number of letters in . At the rule , a step with removes one and stays at the rule , and a step with goes to the output state. So from the computation reaches in exactly steps, where is with its letters removed.
Algorithms and programs
Algorithm C1.1.1.6 (Euclid, TAOCP Algorithm 1.1E). The input is two positive integers and . The output is , the largest positive integer that divides both and .
Node: TAAY27CDTK · Lean: TAOCP.S1_1.E.method, TAOCP.S1_1.E.terminates, TAOCP.S1_1.E.correct, TAOCP.S1_1.E.count_E1 · status: not stated yet
The idea. Divide by . If the remainder is , then divides , and is the answer. If not, the pair has the same greatest common divisor as and a smaller second member, so do the same thing again with .
The steps. The pseudocode of C1, with the Lean definition TAOCP.S1_1.E.step of tamnd/taocp-lean next to it, in the source form of the command knuth_algorithm. Each line of the pseudocode is one label of the Lean code.
Euclid(m, n): -- m >= 1, n >= 1
loop
r := m mod n -- label E1: divide
if r = 0: return n -- label E2: test the remainder
(m, n) := (n, r) -- label E3: shift, then go back to E1
knuth_algorithm E (m n : ℕ) : ℕ requires 0 < m ∧ 0 < n where
var r : ℕ := 0
E1 "Divide." r := m % n
E2 "Test the remainder." if r = 0 then halt n
E3 "Shift." m := n; n := r; goto E1
The Lean state is a label and a store with a field result, and the label done marks the output. The answer is the field result of the output state.
A worked run. Take and . Each row is one pass through the loop.
| Pass | Next | |||
|---|---|---|---|---|
| 1 | 1071 | 462 | 147 | |
| 2 | 462 | 147 | 21 | |
| 3 | 147 | 21 | 0 | return |
The same input in Lean, at the eight steps of TAOCP.S1_1.E.step (three divisions, three tests and two shifts):
#eval TAOCP.S1_1.E.run (TAOCP.S1_1.E.start 1071 462) 8
-- (TAOCP.S1_1.E.Label.done, { m := 147, n := 21, r := 0, result := 21 })
#eval Nat.gcd 1071 462
-- 21
Correctness. The proof uses one lemma.
Lemma. If and , then .
Proof of the lemma. Write with . If divides and , then divides . If divides and , then divides . So the pairs and have the same common divisors, and so the same greatest common divisor. (When , read as .) In Mathlib this is Nat.gcd_rec.
Let and be the inputs. The invariant is
It is true at the first pass, since then and . Suppose it is true at the start of a pass, and the pass does not return. Then , the new pair is , and , , and by the lemma. So the invariant is true at the start of the next pass. When a pass returns, , so divides , and then . By the invariant, the value that the algorithm returns is .
Termination. At each pass that does not return, the new value of is , and . So is a positive integer that gets smaller at each pass. A strictly decreasing sequence of positive integers that starts at has at most members, so the algorithm stops after at most passes. In the Lean code the two facts are the theorems TAOCP.S1_1.E.terminates and TAOCP.S1_1.E.correct.
Cost. Let be the number of passes, that is, the number of divisions. Then the division and the test each run times, and the shift runs times. The bound of the proof above is weak. A better bound comes from a second look at the remainders. Write , , and let be the remainders, so that and .
Claim. If , then for .
Proof of the claim. If , then . If , then the quotient of by is (since ; for this uses ), so .
So for each with . The remainder is at least . Let . If , then , so and . If , then too. In both cases , so
When , the first pass only swaps the two numbers (its remainder is ), so . For example, has the remainders , so , and the bound is . Section 4.5.3 shows that the worst case is a pair of consecutive Fibonacci numbers, as in this example, and that is then about .
Example C1.1.1.7 (the swap step E0, TAOCP Algorithm 1.1E). A first step can be put before the loop: if , swap and . This saves one division when , because the first division of Algorithm 1.1E does nothing in that case but put the larger number first. For the first pass has and gives the pair , so the algorithm makes divisions. With the swap step first, it makes the divisions of the worked run above. The swap step changes the cost, not the result: by the symmetry the output is the same.
Analysis C1.1.1.8 (the average number of divisions , TAOCP Section 1.1). Fix and let be the average number of divisions that Algorithm 1.1E makes on the input when is a positive integer chosen at random. The average is over , since the number of divisions depends only on (proved below). The question is how grows with .
Node: TA7GM8VP9M · status: not stated yet
The idea. The number of divisions on depends only on the remainder of by . So the average over all is a finite average, and is a rational number that a computation can give. The growth of for large is a hard problem, and the book solves it in Section 4.5.3.
Why the average is finite. Let be the number of divisions on the input . If divides , then . If not, the first division gives the remainder and the next pair , so . In both cases depends only on and , and the values give each remainder exactly once (the value gives the remainder ). So the average of over is the same for each , and
A worked computation. For : (the pairs and ), , (the pairs , and ), and . So . For the values for are , so . The same computation gives:
| 1 | 2 | 3 | 4 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|
The value is exercise 1.1-6, so it is not in the table.
The cost of each step. With , the division runs times, the test runs times and the shift runs times. So the average number of runs of the division and of the test is , and the average for the shift is .
The bound and the growth. By the cost bound of Algorithm 1.1E, for each , so . Section 4.5.3 finds the growth exactly: the main term of is , which is about . The proof of that result uses the theory of continued fractions and is out of the reach of Chapter 1.
The exercises
The table has the exercises of Section 1.1. The kind is the class of spec 06.3 that C1 proposes, and the indexer of S0 fixes it in the map. The marker ▶ is the book's mark of a recommended exercise.
| Exercise | Rating | Markers | Kind | Lean | Solution |
|---|---|---|---|---|---|
| 1.1-1 | 10 | K5 | not yet stated | X1, 1.1-1 | |
| 1.1-2 | 15 | K1 | not yet stated | X1, 1.1-2 | |
| 1.1-3 | 20 | K5 | not yet stated | X1, 1.1-3 | |
| 1.1-4 | 16 | K3 | not yet stated | X1, 1.1-4 | |
| 1.1-5 | 12 | ▶ | informal | not yet stated | X1, 1.1-5 |
| 1.1-6 | 20 | K3 | not yet stated | X1, 1.1-6 | |
| 1.1-7 | 21 | ▶ M | K7 | not yet stated | X1, 1.1-7 |
| 1.1-8 | 25 | M | K5 | not yet stated | X1, 1.1-8 |
| 1.1-9 | 30 | ▶ M | informal | not yet stated | X1, 1.1-9 |
The order to do them: 1.1-4 first, as a check of the worked run, then 1.1-1, 1.1-2 and 1.1-3, which are about the steps of Algorithm 1.1E. Exercise 1.1-6 uses the analysis of this chapter, and 1.1-7 asks the same question with the roles of and changed. Exercise 1.1-8 is a method on strings in the form of eq. 1.1(3), and it is the hardest of the set to get right in all details. Exercise 1.1-9 asks for a definition, so it has no single answer.
Lean
The Lean code of Section 1.1 is in tamnd/taocp-lean, at main (commit b48ef97). The file TAOCP/Algorithm/CompMethod.lean has the model of computation, and the file TAOCP/V1/S1_1.lean has Algorithm 1.1E.
TAOCP.CompMethodis the quadruple , with the fieldfixesfor the condition on .TAOCP.CompMethod.IsAlgorithmsays that each computation from an input reaches .TAOCP.CompMethod.run x kis the state of eq. 1.1(1).Terminates,stepsandoutputare the stop, the number and the output.stepsisNat.findof the stop, so it is the least , as in the book.TAOCP.CompMethod.count L x his the number of steps before the output at which the state is in the setL. WithLthe states at one label, it is the frequency of that step. A Lean form of is the average ofcountfor the labelE1over the inputsTAOCP.S1_1.E.start m nwith . It is not yet stated.TAOCP.S1_1.E.methodis Algorithm 1.1E in step format, with the labelsE1,E2,E3anddone. Its inputs are the states atE1with and . The swap step E0 is not part of it. The commandknuth_algorithmalso makesTAOCP.S1_1.E.step,TAOCP.S1_1.E.start,TAOCP.S1_1.E.runandTAOCP.S1_1.E.count.TAOCP.S1_1.E.terminatesandTAOCP.S1_1.E.correctare theorems with proofs: the stop on each input and the output . The theoremTAOCP.S1_1.E.count_E1says that step E1 runsTAOCP.S1_1.E.euclidSteps m ntimes, andTAOCP.S1_1.E.euclidSteps_lebounds this number by . The computation takes steps for runs of step E1.
Two choices of fidelity matter. First, the Lean model does not have effectiveness: the step function is any Lean function. When the step function is a computable Lean function, as TAOCP.S1_1.E.step is, #eval runs it, and this is the form of effectiveness that the project uses. Second, the inputs of TAOCP.S1_1.E.method are states, not pairs of numbers, so the input is the state TAOCP.S1_1.E.start m n. The Mathlib facts that the proofs use are Nat.gcd_rec (the lemma of the correctness proof), Nat.gcd_zero_right, Nat.gcd_dvd_left and Nat.dvd_gcd.
Notes and history
Euclid's algorithm is in Book VII of Euclid's Elements (about 300 B.C.), Propositions 1 and 2, where it works by repeated subtraction. Book X uses the same method on lengths, and there it can fail to stop, as in the example of Section 1.2.1 of C1. The method is probably older than Euclid. The word "algorithm" comes from the name of the Persian mathematician al-Khwarizmi, whose book on arithmetic (about 825) came to Europe in Latin translations.
The definition of an algorithm as a quadruple is the book's own. The methods on strings of eq. 1.1(3) are due to A. A. Markov, in his work on the theory of algorithms (1951 and 1954). Other exact models of the same class are the machines of A. M. Turing (1936) and the lambda calculus of A. Church (1936). The thesis that each of them captures all methods that a person can carry out with pencil and paper is the Church and Turing thesis. It is not a theorem, since "a method that a person can carry out" is not a mathematical object.
G. Lamé proved in 1844 that the number of divisions is at most five times the number of decimal digits of the smaller input, with the Fibonacci numbers as the worst case. The average of was found by H. Heilbronn (1969) and, with the constant term, by J. W. Porter (1975). Section 4.5.3 of the book has the full story.
The project has no errata of Section 1.1 to report.
Section 1.1 of TAOCP opens the book. It gives the first algorithm of the book, Euclid's algorithm for the greatest common divisor, and uses it to say what an algorithm is: first in words, with five properties, and then in the language of sets, as a computational method. This chapter of C1 explains each of these items, proves that Euclid's algorithm is correct and that it stops, and counts its steps.
The source of this page. Something is wrong? Report it.