taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

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.

Contents
  1. Algorithms and Euclid's algorithm

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 (Q,I,Ω,f)(Q, I, \Omega, f) 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 rr is the remainder of mm divided by nn, then mm and nn have the same common divisors as nn and rr. So gcd⁡(m,n)=gcd⁡(n,r)\gcd(m, n) = \gcd(n, r), and the second pair is smaller. Try it by hand on m=84m = 84 and n=36n = 36: the remainder of 8484 divided by 3636 is 1212, and the remainder of 3636 divided by 1212 is 00. So gcd⁡(84,36)=gcd⁡(36,12)=12\gcd(84, 36) = \gcd(36, 12) = 12, since 1212 divides 3636. The algorithm repeats this one step until the remainder is 00.

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 2lg⁡n2 \lg n, and the average for a fixed nn grows like a constant times ln⁡n\ln n.

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 QQ of states and a function ff from QQ to QQ. A run is the sequence x,f(x),f(f(x)),…x, f(x), f(f(x)), \ldots, 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:

  1. Finiteness. For each input, it stops after a finite number of steps.
  2. Definiteness. Each step says exactly what to do, with no doubt, in each case that can occur.
  3. Input. It takes zero or more inputs, from sets that are given in advance.
  4. Output. It gives one or more outputs, which have a stated relation to the inputs.
  5. 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 mm by nn" is effective for integers, but "find the largest prime factor of a number with 10001000 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 mm and nn. Its output is gcd⁡(m,n)\gcd(m, n). 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 k=1,3,5,7,…k = 1, 3, 5, 7, \ldots in turn, add the divisors of kk that are less than kk, and stop when the sum is kk". 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 (Q,I,Ω,f)(Q, I, \Omega, f), where QQ is a set (the states), I⊆QI \subseteq Q is the set of inputs, Ω⊆Q\Omega \subseteq Q is the set of outputs, and f ⁣:Q→Qf\colon Q \to Q is a function (the step) with f(q)=qf(q) = q for each q∈Ωq \in \Omega. The method is an algorithm when the computation from each input x∈Ix \in I 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 ff is one step of the method. The condition f(q)=qf(q) = q on Ω\Omega 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 II, the outputs are Ω\Omega, each step is the value of a function (definiteness), and finiteness is the condition that each computation reaches Ω\Omega. It does not have effectiveness, since ff 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 Q={1,2,3,…}Q = \{1, 2, 3, \ldots\}, I=QI = Q, Ω={1}\Omega = \{1\}, and let f(1)=1f(1) = 1, f(q)=q/2f(q) = q/2 for an even qq, and f(q)=3q+1f(q) = 3q + 1 for an odd q>1q > 1. Then ff leaves the one output state fixed, so (Q,I,Ω,f)(Q, I, \Omega, f) is a computational method. From the input 66 the states are 6,3,10,5,16,8,4,2,16, 3, 10, 5, 16, 8, 4, 2, 1, so the computation stops after 88 steps with the output 11. Whether this method is an algorithm is the Collatz problem. It is open: nobody has proved that each input reaches 11, 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 (Q,I,Ω,f)(Q, I, \Omega, f) be a computational method and let x∈Ix \in I. The computation from xx is the sequence x0,x1,x2,…x_0, x_1, x_2, \ldots below. It stops in kk steps when kk is the least integer with xk∈Ωx_k \in \Omega, and then xkx_k is its output. When no xkx_k is in Ω\Omega, the computation does not stop.

x0=x,xk+1=f(xk)(k≥0).x_0 = x, \qquad x_{k+1} = f(x_k) \quad (k \ge 0).

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 kk is the number of steps, and the output is the first state in Ω\Omega. After that state the sequence does not change: if xk∈Ωx_k \in \Omega, then xk+1=f(xk)=xkx_{k+1} = f(x_k) = x_k, and by induction xj=xkx_j = x_k for each j≥kj \ge k. So it does not matter which state of Ω\Omega 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 kk 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 x=7x = 7 is 7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,1,1,…7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 1, 1, \ldots. The first state in Ω\Omega is x16=1x_{16} = 1, so the computation stops in 1616 steps with the output 11.

Proof that the sequence stays at its output. Let xk∈Ωx_k \in \Omega. For j=kj = k the claim xj=xkx_j = x_k is true. If xj=xkx_j = x_k for some j≥kj \ge k, then xj∈Ωx_j \in \Omega, so xj+1=f(xj)=xj=xkx_{j+1} = f(x_j) = x_j = x_k, because ff leaves each state of Ω\Omega fixed. By induction on jj, xj=xkx_j = x_k for each j≥kj \ge k. □\square

Definition C1.1.1.4 (Euclid's algorithm as a computational method, TAOCP eq. 1.1(2)). Let QQ be the set of the tuples ⟨d⟩\langle d\rangle, ⟨m,n⟩\langle m, n\rangle and ⟨m,n,r⟩\langle m, n, r\rangle of integers with d,m,n≥1d, m, n \ge 1 and 0≤r<n0 \le r < n. Let II be the set of the pairs ⟨m,n⟩\langle m, n\rangle, let Ω\Omega be the set of the one-tuples ⟨d⟩\langle d\rangle, and let

f⟨m,n⟩=⟨m,n,m mod n⟩,f⟨m,n,r⟩={⟨n⟩if r=0,⟨n,r⟩if r>0,f⟨d⟩=⟨d⟩.f\langle m, n\rangle = \langle m, n, m \bmod n\rangle, \qquad f\langle m, n, r\rangle = \begin{cases} \langle n\rangle & \text{if } r = 0,\\ \langle n, r\rangle & \text{if } r > 0,\end{cases} \qquad f\langle d\rangle = \langle d\rangle.

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 ⟨m,n⟩\langle m, n\rangle is the state before a division. A triple ⟨m,n,r⟩\langle m, n, r\rangle is the state after the division, before the test of rr. A one-tuple ⟨d⟩\langle d\rangle is the answer. The function ff maps QQ into QQ: the remainder m mod nm \bmod n is less than nn, and when r>0r > 0 the pair ⟨n,r⟩\langle n, r\rangle 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 mm, nn, rr.

Example. From the input ⟨1071,462⟩\langle 1071, 462\rangle the computation is

⟨1071,462⟩, ⟨1071,462,147⟩, ⟨462,147⟩, ⟨462,147,21⟩, ⟨147,21⟩, ⟨147,21,0⟩, ⟨21⟩.\langle 1071, 462\rangle,\ \langle 1071, 462, 147\rangle,\ \langle 462, 147\rangle,\ \langle 462, 147, 21\rangle,\ \langle 147, 21\rangle,\ \langle 147, 21, 0\rangle,\ \langle 21\rangle.

It stops in 66 steps with the output ⟨21⟩\langle 21\rangle, and indeed gcd⁡(1071,462)=21\gcd(1071, 462) = 21: 1071=32⋅7⋅171071 = 3^2 \cdot 7 \cdot 17 and 462=2⋅3⋅7⋅11462 = 2 \cdot 3 \cdot 7 \cdot 11.

Proof that this is a computational method that is an algorithm. The function ff leaves each ⟨d⟩\langle d\rangle fixed, so (Q,I,Ω,f)(Q, I, \Omega, f) is a computational method. For the stop, give each state the weight w⟨m,n⟩=2nw\langle m, n\rangle = 2n, w⟨m,n,r⟩=2r+1w\langle m, n, r\rangle = 2r + 1 and w⟨d⟩=0w\langle d\rangle = 0. A step from ⟨m,n⟩\langle m, n\rangle goes to the weight 2(m mod n)+1≤2(n−1)+1<2n2(m \bmod n) + 1 \le 2(n - 1) + 1 < 2n. A step from ⟨m,n,r⟩\langle m, n, r\rangle goes to the weight 00 when r=0r = 0, and to the weight 2r<2r+12r < 2r + 1 when r>0r > 0. So the weight gets smaller at each step until the state is in Ω\Omega. A sequence of nonnegative integers that gets smaller at each step has at most w(x)+1w(x) + 1 members, so the computation from each input reaches Ω\Omega. That the output is gcd⁡(m,n)\gcd(m, n) is the correctness proof of Algorithm 1.1E below. □\square

Definition C1.1.1.5 (an effective computational method on strings, TAOCP eq. 1.1(3)). Let AA be a finite set of letters, let A∗A^* be the set of strings of letters of AA, and let N≥0N \ge 0. A method on strings is given by NN rules: for each jj with 0≤j<N0 \le j < N, a rule has two strings θj,φj∈A∗\theta_j, \varphi_j \in A^* and two integers aj,bja_j, b_j with 0≤aj,bj≤N0 \le a_j, b_j \le N. Its states are the pairs (σ,j)(\sigma, j) with σ∈A∗\sigma \in A^* and 0≤j≤N0 \le j \le N. The inputs are the states (σ,0)(\sigma, 0), the outputs are the states (σ,N)(\sigma, N), and

f(σ,j)={(σ,aj)if θj is not a part of σ,(αφjω,bj)if σ=αθjω and α is as short as possible,(σ,N)if j=N.f(\sigma, j) = \begin{cases} (\sigma, a_j) & \text{if } \theta_j \text{ is not a part of } \sigma,\\ (\alpha\varphi_j\omega, b_j) & \text{if } \sigma = \alpha\theta_j\omega \text{ and } \alpha \text{ is as short as possible},\\ (\sigma, N) & \text{if } j = N.\end{cases}

Node: TAF1HD6GRG · status: not stated yet

Explanation. At the rule jj, the method looks for the first place where the string θj\theta_j occurs in σ\sigma. If there is none, it goes to the rule aja_j and does not change σ\sigma. If there is one, it puts φj\varphi_j in place of that first copy of θj\theta_j and goes to the rule bjb_j. 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 A={a,b}A = \{a, b\} and N=1N = 1, with one rule: θ0=b\theta_0 = b, φ0\varphi_0 the empty string, a0=1a_0 = 1 and b0=0b_0 = 0. The rule removes the first bb and comes back to itself. When no bb is left, it goes to the output state. From the input (abba,0)(abba, 0) the computation is

(abba,0), (aba,0), (aa,0), (aa,1),(abba, 0),\ (aba, 0),\ (aa, 0),\ (aa, 1),

so the output is the string aaaa after 33 steps. In general the method removes all the letters bb, and a string with tt letters bb takes t+1t + 1 steps.

Proof that the example method is an algorithm. Let tt be the number of letters bb in σ\sigma. At the rule 00, a step with t>0t > 0 removes one bb and stays at the rule 00, and a step with t=0t = 0 goes to the output state. So from (σ,0)(\sigma, 0) the computation reaches (σ′,1)(\sigma', 1) in exactly t+1t + 1 steps, where σ′\sigma' is σ\sigma with its letters bb removed. □\square

Algorithms and programs

Algorithm C1.1.1.6 (Euclid, TAOCP Algorithm 1.1E). The input is two positive integers mm and nn. The output is gcd⁡(m,n)\gcd(m, n), the largest positive integer that divides both mm and nn.

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 mm by nn. If the remainder is 00, then nn divides mm, and nn is the answer. If not, the pair (n,r)(n, r) has the same greatest common divisor as (m,n)(m, n) and a smaller second member, so do the same thing again with (n,r)(n, r).

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 (m,n,r)(m, n, r) 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 m=1071m = 1071 and n=462n = 462. Each row is one pass through the loop.

Pass mm nn r=m mod nr = m \bmod n Next
1 1071 462 147 (m,n):=(462,147)(m, n) := (462, 147)
2 462 147 21 (m,n):=(147,21)(m, n) := (147, 21)
3 147 21 0 return 2121

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 n≥1n \ge 1 and r=m mod nr = m \bmod n, then gcd⁡(m,n)=gcd⁡(n,r)\gcd(m, n) = \gcd(n, r).

Proof of the lemma. Write m=qn+rm = qn + r with q=⌊m/n⌋q = \lfloor m/n \rfloor. If dd divides mm and nn, then dd divides m−qn=rm - qn = r. If dd divides nn and rr, then dd divides qn+r=mqn + r = m. So the pairs (m,n)(m, n) and (n,r)(n, r) have the same common divisors, and so the same greatest common divisor. (When r=0r = 0, read gcd⁡(n,0)\gcd(n, 0) as nn.) In Mathlib this is Nat.gcd_rec. □\square

Let m0m_0 and n0n_0 be the inputs. The invariant is

m≥1,n≥1,gcd⁡(m,n)=gcd⁡(m0,n0)at the start of each pass.m \ge 1, \quad n \ge 1, \quad \gcd(m, n) = \gcd(m_0, n_0) \qquad \text{at the start of each pass.}

It is true at the first pass, since then m=m0m = m_0 and n=n0n = n_0. Suppose it is true at the start of a pass, and the pass does not return. Then r≠0r \ne 0, the new pair is (n,r)(n, r), and n≥1n \ge 1, r≥1r \ge 1, and gcd⁡(n,r)=gcd⁡(m,n)=gcd⁡(m0,n0)\gcd(n, r) = \gcd(m, n) = \gcd(m_0, n_0) by the lemma. So the invariant is true at the start of the next pass. When a pass returns, r=0r = 0, so nn divides mm, and then gcd⁡(m,n)=n\gcd(m, n) = n. By the invariant, the value nn that the algorithm returns is gcd⁡(m0,n0)\gcd(m_0, n_0).

Termination. At each pass that does not return, the new value of nn is rr, and 0<r<n0 < r < n. So nn is a positive integer that gets smaller at each pass. A strictly decreasing sequence of positive integers that starts at n0n_0 has at most n0n_0 members, so the algorithm stops after at most n0n_0 passes. In the Lean code the two facts are the theorems TAOCP.S1_1.E.terminates and TAOCP.S1_1.E.correct.

Cost. Let kk be the number of passes, that is, the number of divisions. Then the division and the test each run kk times, and the shift runs k−1k - 1 times. The bound k≤n0k \le n_0 of the proof above is weak. A better bound comes from a second look at the remainders. Write r−1=m0r_{-1} = m_0, r0=n0r_0 = n_0, and let r1,r2,…,rkr_1, r_2, \ldots, r_k be the remainders, so that rj+1=rj−1 mod rjr_{j+1} = r_{j-1} \bmod r_j and rk=0r_k = 0.

Claim. If m0≥n0m_0 \ge n_0, then rj+1<rj−1/2r_{j+1} < r_{j-1}/2 for 0≤j<k0 \le j < k.

Proof of the claim. If rj≤rj−1/2r_j \le r_{j-1}/2, then rj+1<rj≤rj−1/2r_{j+1} < r_j \le r_{j-1}/2. If rj>rj−1/2r_j > r_{j-1}/2, then the quotient of rj−1r_{j-1} by rjr_j is 11 (since rj≤rj−1<2rjr_j \le r_{j-1} < 2r_j; for j=0j = 0 this uses m0≥n0m_0 \ge n_0), so rj+1=rj−1−rj<rj−1/2r_{j+1} = r_{j-1} - r_j < r_{j-1}/2. □\square

So r2i<n0/2ir_{2i} < n_0/2^i for each i≥1i \ge 1 with 2i≤k2i \le k. The remainder rk−1r_{k-1} is at least 11. Let i=⌊(k−1)/2⌋i = \lfloor (k-1)/2 \rfloor. If i≥1i \ge 1, then 1≤rk−1≤r2i<n0/2i1 \le r_{k-1} \le r_{2i} < n_0/2^i, so 2i<n02^i < n_0 and i<lg⁡n0i < \lg n_0. If i=0i = 0, then i≤lg⁡n0i \le \lg n_0 too. In both cases (k−2)/2≤i≤lg⁡n0(k-2)/2 \le i \le \lg n_0, so

k≤2lg⁡n0+2when m0≥n0.k \le 2 \lg n_0 + 2 \qquad \text{when } m_0 \ge n_0.

When m0<n0m_0 < n_0, the first pass only swaps the two numbers (its remainder is m0m_0), so k≤2lg⁡m0+3k \le 2 \lg m_0 + 3. For example, (m0,n0)=(13,8)(m_0, n_0) = (13, 8) has the remainders 5,3,2,1,05, 3, 2, 1, 0, so k=5k = 5, and the bound is 2lg⁡8+2=82 \lg 8 + 2 = 8. Section 4.5.3 shows that the worst case is a pair of consecutive Fibonacci numbers, as in this example, and that kk is then about log⁡ϕn0≈1.44lg⁡n0\log_\phi n_0 \approx 1.44 \lg n_0.

Example C1.1.1.7 (the swap step E0, TAOCP Algorithm 1.1E). A first step can be put before the loop: if m<nm < n, swap mm and nn. This saves one division when m<nm < n, because the first division of Algorithm 1.1E does nothing in that case but put the larger number first. For (m,n)=(462,1071)(m, n) = (462, 1071) the first pass has r=462r = 462 and gives the pair (1071,462)(1071, 462), so the algorithm makes 44 divisions. With the swap step first, it makes the 33 divisions of the worked run above. The swap step changes the cost, not the result: by the symmetry gcd⁡(m,n)=gcd⁡(n,m)\gcd(m, n) = \gcd(n, m) the output is the same.

Analysis C1.1.1.8 (the average number of divisions TnT_n, TAOCP Section 1.1). Fix n≥1n \ge 1 and let TnT_n be the average number of divisions that Algorithm 1.1E makes on the input (m,n)(m, n) when mm is a positive integer chosen at random. The average is over m=1,2,…,nm = 1, 2, \ldots, n, since the number of divisions depends only on m mod nm \bmod n (proved below). The question is how TnT_n grows with nn.

Node: TA7GM8VP9M · status: not stated yet

The idea. The number of divisions on (m,n)(m, n) depends only on the remainder of mm by nn. So the average over all mm is a finite average, and TnT_n is a rational number that a computation can give. The growth of TnT_n for large nn is a hard problem, and the book solves it in Section 4.5.3.

Why the average is finite. Let D(m,n)D(m, n) be the number of divisions on the input (m,n)(m, n). If nn divides mm, then D(m,n)=1D(m, n) = 1. If not, the first division gives the remainder r=m mod n>0r = m \bmod n > 0 and the next pair (n,r)(n, r), so D(m,n)=1+D(n,r)D(m, n) = 1 + D(n, r). In both cases D(m,n)D(m, n) depends only on nn and m mod nm \bmod n, and the values m=1,…,nm = 1, \ldots, n give each remainder exactly once (the value m=nm = n gives the remainder 00). So the average of D(m,n)D(m, n) over 1≤m≤Mn1 \le m \le Mn is the same for each M≥1M \ge 1, and

Tn=1n∑m=1nD(m,n).T_n = \frac{1}{n} \sum_{m=1}^{n} D(m, n).

A worked computation. For n=4n = 4: D(1,4)=2D(1, 4) = 2 (the pairs (1,4)(1, 4) and (4,1)(4, 1)), D(2,4)=2D(2, 4) = 2, D(3,4)=3D(3, 4) = 3 (the pairs (3,4)(3, 4), (4,3)(4, 3) and (3,1)(3, 1)), and D(4,4)=1D(4, 4) = 1. So T4=(2+2+3+1)/4=2T_4 = (2 + 2 + 3 + 1)/4 = 2. For n=6n = 6 the values for m=1,…,6m = 1, \ldots, 6 are 2,2,2,3,3,12, 2, 2, 3, 3, 1, so T6=13/6T_6 = 13/6. The same computation gives:

nn 1 2 3 4 6 7 8
TnT_n 11 3/23/2 22 22 13/613/6 20/720/7 11/411/4

The value T5T_5 is exercise 1.1-6, so it is not in the table.

The cost of each step. With k=D(m,n)k = D(m, n), the division runs kk times, the test runs kk times and the shift runs k−1k - 1 times. So the average number of runs of the division and of the test is TnT_n, and the average for the shift is Tn−1T_n - 1.

The bound and the growth. By the cost bound of Algorithm 1.1E, D(m,n)≤2lg⁡n+3D(m, n) \le 2 \lg n + 3 for each m≤nm \le n, so Tn≤2lg⁡n+3T_n \le 2 \lg n + 3. Section 4.5.3 finds the growth exactly: the main term of TnT_n is (12ln⁡2/π2)ln⁡n(12 \ln 2/\pi^2) \ln n, which is about 0.843ln⁡n0.843 \ln n. 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 TnT_n of this chapter, and 1.1-7 asks the same question with the roles of mm and nn 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.CompMethod is the quadruple (Q,I,Ω,f)(Q, I, \Omega, f), with the field fixes for the condition f(q)=qf(q) = q on Ω\Omega. TAOCP.CompMethod.IsAlgorithm says that each computation from an input reaches Ω\Omega.
  • TAOCP.CompMethod.run x k is the state xkx_k of eq. 1.1(1). Terminates, steps and output are the stop, the number kk and the output. steps is Nat.find of the stop, so it is the least kk, as in the book.
  • TAOCP.CompMethod.count L x h is the number of steps before the output at which the state is in the set L. With L the states at one label, it is the frequency of that step. A Lean form of TnT_n is the average of count for the label E1 over the inputs TAOCP.S1_1.E.start m n with 1≤m≤n1 \le m \le n. It is not yet stated.
  • TAOCP.S1_1.E.method is Algorithm 1.1E in step format, with the labels E1, E2, E3 and done. Its inputs are the states at E1 with m>0m > 0 and n>0n > 0. The swap step E0 is not part of it. The command knuth_algorithm also makes TAOCP.S1_1.E.step, TAOCP.S1_1.E.start, TAOCP.S1_1.E.run and TAOCP.S1_1.E.count.
  • TAOCP.S1_1.E.terminates and TAOCP.S1_1.E.correct are theorems with proofs: the stop on each input and the output gcd⁡(m,n)\gcd(m, n). The theorem TAOCP.S1_1.E.count_E1 says that step E1 runs TAOCP.S1_1.E.euclidSteps m n times, and TAOCP.S1_1.E.euclidSteps_le bounds this number by nn. The computation takes 3T−13T - 1 steps for TT 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 (m,n)(m, n) 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 (Q,I,Ω,f)(Q, I, \Omega, f) 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 TnT_n 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.