taocp

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

Volume P1 · Proof, induction and invariants

Recursion and structural induction

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 first
Contents
  1. Recursive definitions
  2. Lists and trees
  3. Recursive algorithms

Recursive definitions

Statement

Definition P1.6.1 (recursion on the natural numbers). A function ff on ℕ\mathbb N is defined by recursion if its value at 00 is given and its value at n+1n + 1 is given by a rule from nn and f(n)f(n):

f(0)=c,f(n+1)=g(n,f(n)).f(0) = c, \qquad f(n + 1) = g(n, f(n)).

The first line is the base and the second is the recursive step.

Lean: Nat.rec is the recursor; a definition by pattern matching on 0 and n + 1 is compiled to it.

Example P1.6.2. The factorial: 0!=10! = 1 and (n+1)!=(n+1)⋅n!(n + 1)! = (n + 1) \cdot n!. The power: x0=1x^0 = 1 and xn+1=x⋅xnx^{n+1} = x \cdot x^n. The sum: ∑k=10ak=0\sum_{k=1}^{0} a_k = 0 and ∑k=1n+1ak=∑k=1nak+an+1\sum_{k=1}^{n+1} a_k = \sum_{k=1}^{n} a_k + a_{n+1}. The values of the factorial are 1,1,2,6,24,120,7201, 1, 2, 6, 24, 120, 720.

Lean: Nat.factorial with Nat.factorial_succ : (n + 1)! = (n + 1) * n ! (Mathlib).

Theorem P1.6.3 (a recursive definition defines one function). For every cc and gg there is exactly one function ff on ℕ\mathbb N with f(0)=cf(0) = c and f(n+1)=g(n,f(n))f(n + 1) = g(n, f(n)) for all nn.

Proof. Uniqueness. Let ff and f′f' both satisfy the rules. Prove f(n)=f′(n)f(n) = f'(n) by induction. Base: f(0)=c=f′(0)f(0) = c = f'(0). Step: if f(k)=f′(k)f(k) = f'(k), then f(k+1)=g(k,f(k))=g(k,f′(k))=f′(k+1)f(k + 1) = g(k, f(k)) = g(k, f'(k)) = f'(k + 1).

Existence. Call a list (y0,…,ym)(y_0, \dots, y_m) of values good if y0=cy_0 = c and yi+1=g(i,yi)y_{i+1} = g(i, y_i) for i<mi < m. By induction on mm there is exactly one good list of each length: the list for m+1m + 1 is the list for mm with g(m,ym)g(m, y_m) added at the end, and the uniqueness is as above. Define f(n)f(n) to be the last value of the good list of length nn. Then f(0)=cf(0) = c, and f(n+1)=g(n,f(n))f(n + 1) = g(n, f(n)) since the good list of length n+1n + 1 extends the good list of length nn. □\square

Definition P1.6.4 (recursion with several previous values). The recursive step may use f(n)f(n) and f(n−1)f(n - 1), as in the Fibonacci numbers F0=0F_0 = 0, F1=1F_1 = 1, Fn+2=Fn+1+FnF_{n+2} = F_{n+1} + F_n, or all of f(0),…,f(n)f(0), \dots, f(n). The theorem holds in the same form, with a proof by strong induction. The definition of a function on the integers n≥1n \ge 1 by f(1)=cf(1) = c and f(n)=g(f(⌊n/2⌋))f(n) = g(f(\lfloor n/2 \rfloor)) is of this kind: it uses a value at a number smaller than nn, not at n−1n - 1.

Example P1.6.5. The number of digits of n≥1n \ge 1 in base 22: T(1)=1T(1) = 1 and T(n)=T(⌊n/2⌋)+1T(n) = T(\lfloor n/2 \rfloor) + 1. The values at 1,2,3,4,7,81, 2, 3, 4, 7, 8 are 1,2,2,3,3,41, 2, 2, 3, 3, 4.

Example P1.6.6 (the sum of the digits). Let s(n)=ns(n) = n for 0≤n<100 \le n < 10 and s(n)=s(⌊n/10⌋)+(n mod 10)s(n) = s(\lfloor n/10 \rfloor) + (n \bmod 10) for n≥10n \ge 10. Then s(2024)=s(202)+4=s(20)+2+4=s(2)+0+2+4=8s(2024) = s(202) + 4 = s(20) + 2 + 4 = s(2) + 0 + 2 + 4 = 8.

A proof about a recursively defined function follows the shape of the definition. A base case for the base, and a step for the step.

Example P1.6.7. Claim: n!≥2n−1n! \ge 2^{n-1} for n≥1n \ge 1. Base: 1!=1=201! = 1 = 2^0. Step: (k+1)!=(k+1)k!≥2⋅2k−1=2k(k + 1)! = (k + 1) k! \ge 2 \cdot 2^{k-1} = 2^k. This is Exercise 4.1-5 in the form of a recursive definition.

Example P1.6.8 (the number of calls). Define a recursive procedure fib(n): if n<2n < 2 return nn; otherwise return fib(n-1) + fib(n-2). The number C(n)C(n) of calls (counting the first) satisfies C(0)=C(1)=1C(0) = C(1) = 1 and C(n)=C(n−1)+C(n−2)+1C(n) = C(n - 1) + C(n - 2) + 1. Claim: C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1. Base: C(0)=1=2F1−1C(0) = 1 = 2F_1 - 1, C(1)=1=2F2−1C(1) = 1 = 2F_2 - 1. Step: C(k+2)=2Fk+2−1+2Fk+1−1+1=2Fk+3−1C(k + 2) = 2F_{k+2} - 1 + 2F_{k+1} - 1 + 1 = 2F_{k+3} - 1. The values for n=0,…,9n = 0, \dots, 9 are 1,1,3,5,9,15,25,41,67,1091, 1, 3, 5, 9, 15, 25, 41, 67, 109, so the procedure makes 109109 calls to compute F9=34F_9 = 34. The number of calls grows as fast as the number computed, which is why this procedure is slow.

Proof

A recursive definition can fail in three ways.

No base case. The rule f(n)=f(n−1)+1f(n) = f(n - 1) + 1 with no value given at 00 does not define a function by this theorem: the constants f(0)=cf(0) = c for any cc all satisfy the rule, so the function is not unique.

A step that does not reach the base. The rule f(n)=f(n+1)f(n) = f(n + 1) refers to a larger number, and it defines nothing. The rule f(n)=f(n/2)f(n) = f(n / 2) for even nn and f(n)=f(3n+1)f(n) = f(3n + 1) for odd nn, with f(1)=1f(1) = 1, is an example with a hidden difficulty: whether it defines a function on all positive integers is the open problem of Collatz. For n=27n = 27 the chain reaches 11 after 111111 steps, and for n=6n = 6 after 88 steps. A definition must be accompanied by a proof that the chain reaches the base case, and for this rule there is none.

Two rules for one input. The rules f(n)=2f(n−1)f(n) = 2f(n - 1) and f(n)=f(n−1)+1f(n) = f(n - 1) + 1 with f(0)=1f(0) = 1 agree at n=1n = 1, where both give 22, and differ at n=2n = 2, where they give 44 and 33. A definition that offers both rules for each n≥1n \ge 1 does not define a function. A recursive definition must give one rule for each nn.

The theorem above is the proof that the usual definitions (factorial, power, Fibonacci) are all right. A definition is correct if each nn falls under one case, the value is computed from smaller arguments, and the chain of arguments reaches the base in finitely many steps. For a rule that uses ⌊n/2⌋\lfloor n/2 \rfloor the last point is true by the well-ordering principle: a decreasing sequence of natural numbers is finite.

Examples

Example P1.6.9 (the Ackermann function). Define A(0,n)=n+1A(0, n) = n + 1, A(m+1,0)=A(m,1)A(m + 1, 0) = A(m, 1) and A(m+1,n+1)=A(m,A(m+1,n))A(m + 1, n + 1) = A(m, A(m + 1, n)). The recursion is not of the form of the theorem, since the second rule refers to A(m,1)A(m, 1) for a large second argument. It defines a function on pairs because the pair (m,n)(m, n) decreases in the lexicographic order: either mm decreases, or mm stays and nn decreases. This order is a well order on pairs of natural numbers (Chapter 7), so each chain reaches a base. The values are A(1,n)=n+2A(1, n) = n + 2, A(2,3)=9A(2, 3) = 9 and A(3,3)=61A(3, 3) = 61. The function grows faster than every primitive recursive function.

Example P1.6.10 (the greatest common divisor). The recursion gcd⁡(m,0)=m\gcd(m, 0) = m and gcd⁡(m,n)=gcd⁡(n,m mod n)\gcd(m, n) = \gcd(n, m \bmod n) for n>0n > 0 is a recursive definition that is not on n−1n - 1 but on a smaller remainder. Section 5.3 shows that the chain ends and that the value is the greatest common divisor.

Example P1.6.11 (a base that is not 00). The Fibonacci recurrence has two base cases. The rule an=an−1+an−2+an−3a_n = a_{n-1} + a_{n-2} + a_{n-3} needs three. A definition with fewer base cases than the rule refers back to gives a function that is not defined at some values.

Exercises

  1. [10] Compute n!n! for n=0,…,8n = 0, \dots, 8 and 2n2^n by the recursive definition of the power for n=0,…,8n = 0, \dots, 8.
  2. [12] Define by recursion the sum S(n)=1+2+⋯+nS(n) = 1 + 2 + \cdots + n and prove S(n)=n(n+1)/2S(n) = n(n + 1)/2.
  3. [14] Define by recursion the function d(n)d(n) that gives the number of digits of n≥1n \ge 1 in base 1010, and compute d(2024)d(2024) and d(106)d(10^6).
  4. [14] Let s(n)s(n) be the sum of the digits in base 1010, defined by recursion. Prove that s(n)≡n(mod9)s(n) \equiv n \pmod 9 and compute s(220)s(2^{20}).
  5. [15] Let a0=1a_0 = 1 and an+1=2an+1a_{n+1} = 2a_n + 1. Find ana_n and prove the formula.
  6. [M18] The procedure fib(n) of the text makes C(n)C(n) calls. Prove that C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1, and find the number of calls for n=20n = 20.
  7. [M20] Show that the two rules f(0)=1f(0) = 1, f(n)=2f(n−1)f(n) = 2f(n - 1) for n≥1n \ge 1 and f(0)=1f(0) = 1, f(n)=f(n−1)+1f(n) = f(n - 1) + 1 define different functions, and find the least nn where they differ.
  8. [M22] Prove the uniqueness part of the theorem for the Fibonacci recursion: two functions with F(0)=0F(0) = 0, F(1)=1F(1) = 1 and the rule for n≥2n \ge 2 are equal.
  9. [M25] Prove that gcd⁡(m,n)\gcd(m, n) as defined by the recursion of the text has the property that each step reduces the second argument, so the recursion ends for n≥0n \ge 0. Compute gcd⁡(2024,1024)\gcd(2024, 1024) by the recursion.
  10. [M25] Compute the Ackermann function for A(1,n)A(1, n), A(2,n)A(2, n) in general: prove that A(1,n)=n+2A(1, n) = n + 2 and A(2,n)=2n+3A(2, n) = 2n + 3.

Lean

A recursive definition in Lean is written by pattern matching, as def f : ℕ → ℕ | 0 => c | n + 1 => g n (f n). Lean accepts it only if the recursion ends, and it checks this with a structural or a well-founded argument. A definition of the Ackermann function is accepted because the pair decreases in the lexicographic order. The definition def collatz : ℕ → ℕ with the rule of the text is not accepted without a proof that it ends, since no such proof is known.

Notes and history

The recursion theorem for the natural numbers is due to Dedekind (1888), who proved it from the axioms and saw its role. The function of Ackermann is from 1928 (in the form with three arguments), and the two-argument form is due to Peter. The problem of Collatz is from 1937 and is open. TAOCP defines the factorial and the Fibonacci numbers by recursive rules in Sections 1.2.5 and 1.2.8.

Lists and trees

Statement

Definition P1.6.12 (a recursively defined set). A set is defined recursively by constructors: a list of rules of the form "this is an element" (base rules) and "if x1,…,xkx_1, \dots, x_k are elements, so is c(x1,…,xk)c(x_1, \dots, x_k)" (step rules), together with the clause that nothing else is an element. The elements are exactly the objects that are built by finitely many uses of the rules.

Definition P1.6.13 (lists). Let AA be a set (of letters). The set A∗A^* of lists over AA is defined by two rules: the empty list nil\mathrm{nil} is a list, and if a∈Aa \in A and xx is a list then cons(a,x)\mathrm{cons}(a, x) is a list. Write [a1,…,an][a_1, \dots, a_n] for cons(a1,cons(a2,…cons(an,nil)))\mathrm{cons}(a_1, \mathrm{cons}(a_2, \dots \mathrm{cons}(a_n, \mathrm{nil}))).

Lean: the type List α with the constructors List.nil and List.cons (Lean core).

Definition P1.6.14 (functions on lists). A function on lists is defined by one case for each constructor.

  • Length: len(nil)=0\mathrm{len}(\mathrm{nil}) = 0 and len(cons(a,x))=1+len(x)\mathrm{len}(\mathrm{cons}(a, x)) = 1 + \mathrm{len}(x).
  • Append: app(nil,y)=y\mathrm{app}(\mathrm{nil}, y) = y and app(cons(a,x),y)=cons(a,app(x,y))\mathrm{app}(\mathrm{cons}(a, x), y) = \mathrm{cons}(a, \mathrm{app}(x, y)).
  • Reverse: rev(nil)=nil\mathrm{rev}(\mathrm{nil}) = \mathrm{nil} and rev(cons(a,x))=app(rev(x),[a])\mathrm{rev}(\mathrm{cons}(a, x)) = \mathrm{app}(\mathrm{rev}(x), [a]).

Lean: List.length, List.append (written ++) and List.reverse, with List.length_append, List.reverse_append, List.reverse_reverse and List.append_assoc for the laws below.

Example P1.6.15. app([1,2],[3])=[1,2,3]\mathrm{app}([1, 2], [3]) = [1, 2, 3] and rev([1,2,3])=app(rev([2,3]),[1])=app(app(rev([3]),[2]),[1])=[3,2,1]\mathrm{rev}([1, 2, 3]) = \mathrm{app}(\mathrm{rev}([2, 3]), [1]) = \mathrm{app}(\mathrm{app}(\mathrm{rev}([3]), [2]), [1]) = [3, 2, 1].

Theorem P1.6.16 (the principle of structural induction for lists). Let P(x)P(x) be a statement about lists. If P(nil)P(\mathrm{nil}) holds, and for all a∈Aa \in A and lists xx the statement P(x)→P(cons(a,x))P(x) \to P(\mathrm{cons}(a, x)) holds, then P(x)P(x) holds for every list xx.

Lean: the tactic induction xs with | nil => ... | cons a xs ih => ... (Lean core).

Proof. Every list has a length n≥0n \ge 0 (the number of uses of cons\mathrm{cons}). Prove by induction on nn that P(x)P(x) holds for each list of length nn. For n=0n = 0 the list is nil\mathrm{nil}. A list of length n+1n + 1 is cons(a,x)\mathrm{cons}(a, x) with xx of length nn, for which P(x)P(x) holds by the hypothesis of the induction, and the step gives P(cons(a,x))P(\mathrm{cons}(a, x)). □\square

Theorem P1.6.17 (laws of lists). For all lists x,y,zx, y, z:

  1. app(x,nil)=x\mathrm{app}(x, \mathrm{nil}) = x;
  2. app(app(x,y),z)=app(x,app(y,z))\mathrm{app}(\mathrm{app}(x, y), z) = \mathrm{app}(x, \mathrm{app}(y, z));
  3. len(app(x,y))=len(x)+len(y)\mathrm{len}(\mathrm{app}(x, y)) = \mathrm{len}(x) + \mathrm{len}(y);
  4. rev(app(x,y))=app(rev(y),rev(x))\mathrm{rev}(\mathrm{app}(x, y)) = \mathrm{app}(\mathrm{rev}(y), \mathrm{rev}(x));
  5. rev(rev(x))=x\mathrm{rev}(\mathrm{rev}(x)) = x.

Proof. Each by structural induction on xx, using the definitions.

  1. For x=nilx = \mathrm{nil}: app(nil,nil)=nil\mathrm{app}(\mathrm{nil}, \mathrm{nil}) = \mathrm{nil}. For cons(a,x)\mathrm{cons}(a, x): app(cons(a,x),nil)=cons(a,app(x,nil))=cons(a,x)\mathrm{app}(\mathrm{cons}(a, x), \mathrm{nil}) = \mathrm{cons}(a, \mathrm{app}(x, \mathrm{nil})) = \mathrm{cons}(a, x) by the hypothesis.
  2. For x=nilx = \mathrm{nil} both sides equal app(y,z)\mathrm{app}(y, z). For cons(a,x)\mathrm{cons}(a, x) both sides are cons(a,app(app(x,y),z))\mathrm{cons}(a, \mathrm{app}(\mathrm{app}(x, y), z)) and cons(a,app(x,app(y,z)))\mathrm{cons}(a, \mathrm{app}(x, \mathrm{app}(y, z))), which are equal by the hypothesis.
  3. For nil\mathrm{nil}: len(y)=0+len(y)\mathrm{len}(y) = 0 + \mathrm{len}(y). For cons(a,x)\mathrm{cons}(a, x): 1+len(app(x,y))=1+len(x)+len(y)1 + \mathrm{len}(\mathrm{app}(x, y)) = 1 + \mathrm{len}(x) + \mathrm{len}(y).
  4. For nil\mathrm{nil}: rev(y)=app(rev(y),nil)\mathrm{rev}(y) = \mathrm{app}(\mathrm{rev}(y), \mathrm{nil}) by law 1. For cons(a,x)\mathrm{cons}(a, x): rev(cons(a,app(x,y)))=app(rev(app(x,y)),[a])=app(app(rev(y),rev(x)),[a])\mathrm{rev}(\mathrm{cons}(a, \mathrm{app}(x, y))) = \mathrm{app}(\mathrm{rev}(\mathrm{app}(x, y)), [a]) = \mathrm{app}(\mathrm{app}(\mathrm{rev}(y), \mathrm{rev}(x)), [a]), which by law 2 is app(rev(y),app(rev(x),[a]))=app(rev(y),rev(cons(a,x)))\mathrm{app}(\mathrm{rev}(y), \mathrm{app}(\mathrm{rev}(x), [a])) = \mathrm{app}(\mathrm{rev}(y), \mathrm{rev}(\mathrm{cons}(a, x))).
  5. For nil\mathrm{nil} it is immediate. For cons(a,x)\mathrm{cons}(a, x): rev(rev(cons(a,x)))=rev(app(rev(x),[a]))=app(rev([a]),rev(rev(x)))=app([a],x)=cons(a,x)\mathrm{rev}(\mathrm{rev}(\mathrm{cons}(a, x))) = \mathrm{rev}(\mathrm{app}(\mathrm{rev}(x), [a])) = \mathrm{app}(\mathrm{rev}([a]), \mathrm{rev}(\mathrm{rev}(x))) = \mathrm{app}([a], x) = \mathrm{cons}(a, x), by law 4 and the hypothesis. □\square

The order of the laws is the order of their proofs: law 4 uses laws 1 and 2, and law 5 uses law 4.

Definition P1.6.18 (full binary trees). The set of binary trees is defined by two rules: a leaf ∙\bullet is a tree, and if LL and RR are trees, then the node node(L,R)\mathrm{node}(L, R) is a tree. A node is an internal node, and LL and RR are its left and right subtrees.

Lean: inductive BTree | leaf : BTree | node : BTree → BTree → BTree, with induction t with as the principle.

Definition P1.6.19 (functions on trees).

  • Leaves: ℓ(∙)=1\ell(\bullet) = 1 and ℓ(node(L,R))=ℓ(L)+ℓ(R)\ell(\mathrm{node}(L, R)) = \ell(L) + \ell(R).
  • Internal nodes: i(∙)=0i(\bullet) = 0 and i(node(L,R))=1+i(L)+i(R)i(\mathrm{node}(L, R)) = 1 + i(L) + i(R).
  • Height: h(∙)=0h(\bullet) = 0 and h(node(L,R))=1+max⁡(h(L),h(R))h(\mathrm{node}(L, R)) = 1 + \max(h(L), h(R)).

Theorem P1.6.20 (structural induction for trees). If P(∙)P(\bullet) holds, and P(L)∧P(R)→P(node(L,R))P(L) \wedge P(R) \to P(\mathrm{node}(L, R)) for all trees LL and RR, then P(T)P(T) holds for every tree TT.

Proof. By strong induction on the number of nodes (internal and leaves) of TT: the subtrees LL and RR of node(L,R)\mathrm{node}(L, R) have fewer nodes than the tree, so the strong hypothesis applies to both. □\square

Theorem P1.6.21 (counting in trees). For every tree TT: ℓ(T)=i(T)+1\ell(T) = i(T) + 1 and ℓ(T)≤2h(T)\ell(T) \le 2^{h(T)}.

Proof. By structural induction. For the leaf: 1=0+11 = 0 + 1 and 1≤201 \le 2^0. For node(L,R)\mathrm{node}(L, R) with the hypothesis for LL and RR:

  • ℓ=ℓ(L)+ℓ(R)=(i(L)+1)+(i(R)+1)=(1+i(L)+i(R))+1=i+1\ell = \ell(L) + \ell(R) = (i(L) + 1) + (i(R) + 1) = (1 + i(L) + i(R)) + 1 = i + 1;
  • ℓ=ℓ(L)+ℓ(R)≤2h(L)+2h(R)≤2⋅2max⁡(h(L),h(R))=21+max⁡(h(L),h(R))=2h\ell = \ell(L) + \ell(R) \le 2^{h(L)} + 2^{h(R)} \le 2 \cdot 2^{\max(h(L), h(R))} = 2^{1 + \max(h(L), h(R))} = 2^h. □\square

Example P1.6.22. The tree node(node(∙,∙),∙)\mathrm{node}(\mathrm{node}(\bullet, \bullet), \bullet) has 33 leaves, 22 internal nodes and height 22, and 3=2+13 = 2 + 1 and 3≤223 \le 2^2. The number of trees with nn internal nodes is 1,1,2,5,14,42,132,4291, 1, 2, 5, 14, 42, 132, 429 for n=0,…,7n = 0, \dots, 7 (the Catalan numbers, computed by a program that counts the choices of the sizes of the subtrees).

Proof

A proof by structural induction has the plan: name the principle and the statement; one case for each constructor; in the case of a constructor with subobjects, assume the statement for each subobject. The base cases are the constructors without subobjects (nil, leaf). The proof is correct because every object is built in finitely many steps, and so the principle follows from the induction on the number of steps, as shown for lists.

The choice of the object of the induction matters. The laws above are proved by induction on xx, the first argument of app\mathrm{app}, and not on yy, because the definition of app\mathrm{app} recurses on the first argument. An induction on yy would not unfold the definition. A rule: induct on the argument that the function recurses on.

An auxiliary lemma is often needed, as law 1 for law 4. If a proof by induction gets stuck on an expression that the definitions do not simplify, find the lemma that simplifies it and prove the lemma first.

Examples

Example P1.6.23 (the number of nodes). A tree has ℓ+i=2i+1\ell + i = 2i + 1 nodes in all. So a tree with 1010 leaves has 99 internal nodes and 1919 nodes in all. Since ℓ≤2h\ell \le 2^h, a tree with nn leaves has height at least ⌈log⁡2n⌉\lceil \log_2 n \rceil. For n=10n = 10 the height is at least 44.

Example P1.6.24 (the reverse takes quadratic time). The definition of rev\mathrm{rev} calls app\mathrm{app} on a list of the length of rev(x)\mathrm{rev}(x), so the number of cons steps that app\mathrm{app} performs to reverse a list of nn elements is 0+1+⋯+(n−1)=n(n−1)/20 + 1 + \cdots + (n - 1) = n(n - 1)/2, by the formula of Chapter 4. For n=100n = 100 it is 49504950. A better definition uses an accumulator: rv(nil,y)=y\mathrm{rv}(\mathrm{nil}, y) = y and rv(cons(a,x),y)=rv(x,cons(a,y))\mathrm{rv}(\mathrm{cons}(a, x), y) = \mathrm{rv}(x, \mathrm{cons}(a, y)), with rev(x)=rv(x,nil)\mathrm{rev}(x) = \mathrm{rv}(x, \mathrm{nil}). Its correctness is the statement rv(x,y)=app(rev(x),y)\mathrm{rv}(x, y) = \mathrm{app}(\mathrm{rev}(x), y) for all xx and yy, a stronger claim in the sense of Chapter 4, Section 2: the plain claim rv(x,nil)=rev(x)\mathrm{rv}(x, \mathrm{nil}) = \mathrm{rev}(x) cannot be proved by induction on xx since the second argument changes.

Example P1.6.25 (arithmetic expressions). The expressions built from numbers and the operations ++ and ×\times are a recursively defined set: a number is an expression, and if ee and ff are expressions so are (e+f)(e + f) and (e×f)(e \times f). Claim: each expression has an equal number of left and right brackets, and the number of operators is one less than the number of numbers. Both are proved by structural induction, as for trees: the second is the law ℓ=i+1\ell = i + 1 where the numbers are the leaves.

Exercises

  1. [10] Compute app([1,2],[3,4])\mathrm{app}([1, 2], [3, 4]), rev([1,2,3,4])\mathrm{rev}([1, 2, 3, 4]) and len([5,6,7])\mathrm{len}([5, 6, 7]) from the definitions.
  2. [12] Prove law 1: app(x,nil)=x\mathrm{app}(x, \mathrm{nil}) = x.
  3. [14] Prove law 2, the associativity of the append.
  4. [14] Prove law 3, the length of an append, and find the length of rev(x)\mathrm{rev}(x) in terms of the length of xx.
  5. [15] Prove that a tree with ii internal nodes has 2i+12i + 1 nodes in all, and find the number of nodes of a tree with 5050 leaves.
  6. [M18] Prove law 4 and law 5 for the reverse.
  7. [M20] Prove that a tree of height hh has at most 2h2^h leaves and at most 2h+1−12^{h+1} - 1 nodes in all.
  8. [M22] Define rv(x,y)\mathrm{rv}(x, y) by the accumulator rule and prove that rv(x,y)=app(rev(x),y)\mathrm{rv}(x, y) = \mathrm{app}(\mathrm{rev}(x), y) for all lists. Deduce that rv(x,nil)=rev(x)\mathrm{rv}(x, \mathrm{nil}) = \mathrm{rev}(x).
  9. [M25] List the five trees with 33 internal nodes and compute the height and the number of leaves of each.
  10. [M25] Let the set SS of strings of brackets be defined by: the empty string is in SS; if uu and vv are in SS, so is (u)v(u)v. Prove that each string in SS has equally many left and right brackets, and that in each initial segment the number of left brackets is at least that of the right ones.

Lean

For lists, induction xs with | nil => simp | cons a xs ih => simp [ih] proves many of the laws above, and simp knows List.length_append, List.reverse_append and List.reverse_reverse. For a new type of trees the statement inductive BTree with the two constructors produces the induction principle, and the proof of ℓ=i+1\ell = i + 1 is induction t with | leaf => ... | node l r ihl ihr => ...with the functions leaves and internal defined by the equations of the text. The exact script depends on the definitions, so write the two functions first and test the script in the version that you use.

Notes and history

The definition of a set by constructors and the principle of structural induction were made precise in the work of Burstall (1969), who used it for proofs of programs. The type of lists with nil and cons is the base of the language Lisp (McCarthy, 1958). TAOCP treats lists and trees in Chapter 2 of Volume 1, and the identity ℓ=i+1\ell = i + 1 is the fact that an extended binary tree with nn internal nodes has n+1n + 1 external nodes (Section 2.3).

Recursive algorithms

Statement

A recursive procedure is a procedure that calls itself on a smaller argument. It is a recursive definition of a function, with the calls as the steps, and it is proved correct by the induction that fits its recursion: weak induction for a call on n−1n - 1, strong induction for a call on ⌊n/2⌋\lfloor n/2 \rfloor or on a remainder, and structural induction for a call on a part of a list or a tree.

Definition P1.6.26 (a proof of a recursive procedure). To prove that a procedure P(x)\mathrm{P}(x) returns a value with the property Q(x)Q(x) for every legal input xx, prove two things. Termination: each chain of calls ends, which follows if the argument decreases in a well-ordered measure (a natural number) at each call. Correctness: by induction on the measure, assume that every call on a smaller argument returns a value with the property, and show that the value returned for xx has it.

Example P1.6.27 (the power by squaring). The procedure pw(x,n)\mathrm{pw}(x, n) for n≥0n \ge 0 is: if n=0n = 0 return 11; if nn is even let y=pw(x,n/2)y = \mathrm{pw}(x, n/2) and return y⋅yy \cdot y; if nn is odd return x⋅pw(x,n−1)x \cdot \mathrm{pw}(x, n - 1). Claim: pw(x,n)=xn\mathrm{pw}(x, n) = x^n. The measure is nn. Termination: the calls are on n/2<nn/2 < n and n−1<nn - 1 < n (for n≥1n \ge 1). Correctness by strong induction on nn: for n=0n = 0 the value is 1=x01 = x^0. For even n≥2n \ge 2 the hypothesis gives y=xn/2y = x^{n/2} and y⋅y=xny \cdot y = x^n. For odd nn the hypothesis gives pw(x,n−1)=xn−1\mathrm{pw}(x, n - 1) = x^{n-1}, and x⋅xn−1=xnx \cdot x^{n-1} = x^n.

Theorem P1.6.28 (the cost of the power). For n≥1n \ge 1 the procedure pw(x,n)\mathrm{pw}(x, n) makes ⌊log⁡2n⌋+ν(n)\lfloor \log_2 n \rfloor + \nu(n) multiplications, where ν(n)\nu(n) is the number of 11s in the binary form of nn.

Proof. Let M(n)M(n) be the number of multiplications. Then M(0)=0M(0) = 0, M(n)=M(n/2)+1M(n) = M(n/2) + 1 for even n≥2n \ge 2 and M(n)=M(n−1)+1M(n) = M(n - 1) + 1 for odd nn. Strong induction. For n=1n = 1: M(1)=M(0)+1=1=0+1M(1) = M(0) + 1 = 1 = 0 + 1. For even n≥2n \ge 2: ⌊log⁡2(n/2)⌋=⌊log⁡2n⌋−1\lfloor \log_2 (n/2) \rfloor = \lfloor \log_2 n \rfloor - 1 and ν(n/2)=ν(n)\nu(n/2) = \nu(n), so M(n)=⌊log⁡2n⌋−1+ν(n)+1M(n) = \lfloor \log_2 n \rfloor - 1 + \nu(n) + 1. For odd n≥3n \ge 3: ⌊log⁡2(n−1)⌋=⌊log⁡2n⌋\lfloor \log_2 (n - 1) \rfloor = \lfloor \log_2 n \rfloor and ν(n−1)=ν(n)−1\nu(n - 1) = \nu(n) - 1, so M(n)=⌊log⁡2n⌋+ν(n)−1+1M(n) = \lfloor \log_2 n \rfloor + \nu(n) - 1 + 1. □\square

For n=1000=11111010002n = 1000 = 1111101000_2 the count is 9+6=159 + 6 = 15, against 999999 for the product of 10001000 factors. For n=100n = 100 it is 6+3=96 + 3 = 9.

Example P1.6.29 (the towers of Hanoi). There are three pegs and nn disks of different sizes on the first peg, the smaller above the larger. A move takes the top disk of one peg to another peg and never puts a disk on a smaller one. The task is to move all disks to the second peg. The procedure H(n,a,b,c)\mathrm{H}(n, a, b, c) for n≥0n \ge 0 moves nn disks from peg aa to peg bb using peg cc: if n=0n = 0 do nothing; otherwise do H(n−1,a,c,b)\mathrm{H}(n - 1, a, c, b), move one disk from aa to bb, do H(n−1,c,b,a)\mathrm{H}(n - 1, c, b, a).

Theorem P1.6.30 (Hanoi). H(n,a,b,c)\mathrm{H}(n, a, b, c) moves the nn top disks of aa to bb by 2n−12^n - 1 legal moves, and no solution has fewer moves.

Proof. The number of moves is H(0)=0H(0) = 0 and H(n)=2H(n−1)+1H(n) = 2H(n - 1) + 1, so H(n)=2n−1H(n) = 2^n - 1 by induction (H(k+1)=2(2k−1)+1=2k+1−1H(k + 1) = 2(2^k - 1) + 1 = 2^{k+1} - 1). Correctness by induction on nn: for the nn top disks, the first call moves the n−1n - 1 smaller ones to cc (legal, since they are above the largest, which lies still on aa and which does not obstruct); the move of the largest disk is legal because bb has no smaller disk on top; the second call moves the n−1n - 1 disks from cc onto the largest on bb, and no disk is bigger than a disk that it is put on. For minimality, let m(n)m(n) be the least number of moves of any solution. The largest disk must move at least once. Just before its first move, the n−1n - 1 other disks are all on the third peg, so at least m(n−1)m(n - 1) moves have been made before it (the smaller disks move as in a game with n−1n - 1 disks). After its last move they are all on the third peg again, and at least m(n−1)m(n - 1) more moves are needed to put them on it. So m(n)≥2m(n−1)+1m(n) \ge 2m(n - 1) + 1, and m(n)≥2n−1m(n) \ge 2^n - 1 by induction. □\square

Example P1.6.31. For H(3,a,b,c)\mathrm{H}(3, a, b, c) the moves, written as (from, to), are (a,b),(a,c),(b,c),(a,b),(c,a),(c,b),(a,b)(a, b), (a, c), (b, c), (a, b), (c, a), (c, b), (a, b), and 7=23−17 = 2^3 - 1. For n=10n = 10 the number is 10231023, and for n=64n = 64 it is 1844674407370955161518446744073709551615.

Example P1.6.32 (binary search). A sorted array of nn keys is searched for a key xx. The procedure compares xx with the middle key, and continues in the left half or the right half. Let C(n)C(n) be the greatest number of comparisons for an array of nn keys. Then C(0)=0C(0) = 0 and C(n)≤C(⌊n/2⌋)+1C(n) \le C(\lfloor n/2 \rfloor) + 1 for n≥1n \ge 1 since each half has at most ⌊n/2⌋\lfloor n/2 \rfloor keys. By strong induction C(n)≤⌊log⁡2n⌋+1C(n) \le \lfloor \log_2 n \rfloor + 1: if 2m≤n<2m+12^m \le n < 2^{m+1}, then ⌊n/2⌋<2m\lfloor n/2 \rfloor < 2^m, so C(⌊n/2⌋)≤mC(\lfloor n/2 \rfloor) \le m (for n≥2n \ge 2, by the hypothesis) and C(n)≤m+1C(n) \le m + 1. A program that tests every key in arrays of n=1,2,3,7,8,15,100,1000n = 1, 2, 3, 7, 8, 15, 100, 1000 keys finds the worst cases 1,2,2,3,4,4,7,101, 2, 2, 3, 4, 4, 7, 10, which are equal to the bound.

Proof

A recursive procedure is replaced by a loop when the recursive call is the last thing that the procedure does (tail recursion), or when the procedure can be arranged to be so by a new argument, an accumulator. The loop is correct by a statement that holds before each pass, an invariant (Chapter 8).

Example P1.6.33 (the power as a loop). Let r←1r \gets 1, b←xb \gets x, e←ne \gets n. While e>0e > 0: if ee is odd, r←r⋅br \gets r \cdot b; then b←b⋅bb \gets b \cdot b and e←⌊e/2⌋e \gets \lfloor e/2 \rfloor. The invariant is r⋅be=xnr \cdot b^e = x^n. At the start it is 1⋅xn=xn1 \cdot x^n = x^n. In a pass with ee even, rbe=r(b2)e/2r b^e = r (b^2)^{e/2}. In a pass with ee odd, rbe=(rb)(b2)(e−1)/2r b^e = (rb) (b^2)^{(e-1)/2} and ⌊e/2⌋=(e−1)/2\lfloor e/2 \rfloor = (e - 1)/2. When e=0e = 0 the invariant is r=xnr = x^n. For x=3x = 3 and n=10n = 10 the values of ee are 10,5,2,1,010, 5, 2, 1, 0, and rr becomes 32=93^2 = 9 and then 9⋅38=310=590499 \cdot 3^8 = 3^{10} = 59049.

Example P1.6.34 (Euclid's algorithm). The procedure E(m,n)\mathrm{E}(m, n): if n=0n = 0 return mm, else return E(n,m mod n)\mathrm{E}(n, m \bmod n) is tail recursive, and the loop is Algorithm 1.1E of TAOCP, with the invariant gcd⁡(m,n)=gcd⁡(M,N)\gcd(m, n) = \gcd(M, N).

The converse is not always so simple. A recursion such as Hanoi, with two calls, does not become a loop without a stack. The depth of the recursion, the length of the longest chain of calls, is the amount of memory used by the stack: it is nn for Hanoi and about log⁡2n\log_2 n for binary search.

Examples

Example P1.6.35 (a procedure that is not correct). Let S(n)\mathrm{S}(n) be: if n=0n = 0 return 00, else return n+S(n−2)n + \mathrm{S}(n - 2). For n=1n = 1 the chain goes 1,−1,−3,…1, -1, -3, \dots and never reaches 00. The termination proof fails: the measure nn does not decrease to a well-ordered base, since n−2n - 2 may be negative. For even nn the procedure is right and returns n(n+2)/4n(n + 2)/4.

Example P1.6.36 (a count by recursion). The number c(n)c(n) of ways to climb nn steps by steps of 11 or 22 satisfies c(0)=1c(0) = 1, c(1)=1c(1) = 1 and c(n)=c(n−1)+c(n−2)c(n) = c(n - 1) + c(n - 2), so c(n)=Fn+1c(n) = F_{n+1}. For n=10n = 10 there are 8989 ways.

Example P1.6.37 (merge of two lists). The recursive merge of two sorted lists: mg(nil,y)=y\mathrm{mg}(\mathrm{nil}, y) = y, mg(x,nil)=x\mathrm{mg}(x, \mathrm{nil}) = x, and for x=cons(a,x′)x = \mathrm{cons}(a, x'), y=cons(b,y′)y = \mathrm{cons}(b, y') it returns cons(a,mg(x′,y))\mathrm{cons}(a, \mathrm{mg}(x', y)) if a≤ba \le b and cons(b,mg(x,y′))\mathrm{cons}(b, \mathrm{mg}(x, y')) otherwise. The measure is len(x)+len(y)\mathrm{len}(x) + \mathrm{len}(y), which decreases by 11 at each call. By induction on the measure the result is sorted and has the elements of both lists.

Exercises

  1. [10] Trace pw(2,10)\mathrm{pw}(2, 10) by hand and count the multiplications.
  2. [12] Write the moves of H(3,a,b,c)\mathrm{H}(3, a, b, c) that move three disks from aa to bb.
  3. [14] Prove that H(n,a,b,c)\mathrm{H}(n, a, b, c) makes 2n−12^n - 1 moves, and find the time for n=64n = 64 at one move per second, in years (a computer is enough).
  4. [14] Prove that the number of ways to climb nn steps with steps of 11 or 22 is Fn+1F_{n+1}.
  5. [15] Prove that the loop for the power has the invariant r⋅be=xnr \cdot b^e = x^n, and trace it for x=2x = 2 and n=13n = 13.
  6. [M18] Prove that pw(x,n)\mathrm{pw}(x, n) makes ⌊log⁡2n⌋+ν(n)\lfloor \log_2 n \rfloor + \nu(n) multiplications and find n≤100n \le 100 for which it is greatest.
  7. [M20] Prove that binary search on nn sorted keys needs at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 comparisons.
  8. [M22] Prove that the recursive merge of two sorted lists returns a sorted list with all elements of both.
  9. [M24] Prove that the procedure E(m,n)\mathrm{E}(m, n) of the text returns gcd⁡(m,n)\gcd(m, n) for m,n≥0m, n \ge 0, and that it makes at most n+1n + 1 calls for n≥1n \ge 1. Count the calls for (89,55)(89, 55).
  10. [M25] Prove that Hanoi has a unique shortest solution, by showing that in each shortest solution the largest disk moves exactly once.

Lean

A recursive function with a call on a smaller argument is accepted when Lean can prove that the argument decreases, by termination_by and decreasing_by for a measure that is not the structural one. The function Nat.gcd is defined by well-founded recursion in this way. The correctness of pw as pw x n = x ^ n is proved by Nat.strong_induction_on with a case split on the parity, as in the proof of this section.

Notes and history

The towers of Hanoi are a puzzle of Lucas of 1883, and the story of the monks and the sixty-four disks goes with it. The method of binary search was described by Mauchly in 1946 and the first fully correct programs came later, a point that Knuth makes in Volume 3. The power by squaring is old, and TAOCP discusses it with its history in Section 4.6.3. The loop and the invariant are the subject of Chapter 8.

A recursive definition describes an object by a rule that uses smaller objects of the same kind. The factorial, the Fibonacci numbers, a list and a tree are all defined in this way. A proof about such an object follows its definition, and the proof method that results is structural induction, a form of the induction of Chapters 4 and 5.

Section 1 treats the recursive definition of a function on the natural numbers, proves that such a definition defines exactly one function, and shows what goes wrong when the recursion does not reach a base case. Section 2 defines lists and binary trees as recursively defined sets, defines the length, the append, the reverse, the number of leaves and the height, and proves their laws by structural induction. Section 3 turns to programs: recursive procedures, their proofs by induction, the towers of Hanoi, binary search, and the loop that replaces a recursion.

The chapter assumes Chapters 1 to 5. The spine texts are Velleman, How to Prove It, Section 6.3, and Lehman, Leighton and Meyer, Mathematics for Computer Science, Chapters 6 and 7. TAOCP uses the structures of Section 2 in Chapter 2 of Volume 1, on information structures, and the recursion of Section 3 in many of its algorithms.

The source of this page. Something is wrong? Report it.