---
title: "Induction, Recursion and Termination"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 11
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 11 — Induction, Recursion and Termination

A function reverses a list; applied twice, it should give the list back. A program can check this on three thousand lists in a fraction of a second, and it does below, but lists have no largest length: a check, however long, says nothing about the lists it did not try. This chapter gives the two tools that cover every case. [Structural induction](#def-b1-induction-and-termination-structural) proves a property of every list, tree or formula by following the rules that build them. [Well-founded orders](#def-b1-induction-and-termination-well-founded) prove that a loop or a recursive function stops, by attaching to each state a quantity that cannot decrease forever.

**You already know.**

To prove a property $P(n)$ for every natural number $n$ by induction, prove $P(0)$, and prove $P(n + 1)$ from $P(n)$ (or from all of $P(0), \dots, P(n)$: strong induction). An order relation is reflexive, antisymmetric and transitive. A recursive function calls itself on smaller arguments and stops on base cases.

## 11.1 Inductively defined sets

**Definition 11.1 (Inductively defined set).**

A set is *inductively defined* by rules when it is the smallest set closed under them: *base rules* put given elements in the set, and *construction rules* build an element from elements already in it. Every element is obtained by finitely many applications of the rules.

The natural numbers are defined by the base rule “0” and the rule “if $n$, then $n + 1$”; the lists of the elements of a set $A$ by “the empty list” and “if $x \in A$ and $\ell$ is a list, then $x$ followed by $\ell$”; the [propositional formulas](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-formula) of [Chapter 10](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#ch-b1-propositional-logic) by their variables and [connectives](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-formula).

**Definition 11.2 (Rooted tree, root, child, leaf, internal node, subtree).**

A *rooted tree* is a node, its *root*, holding a key and a finite sequence of rooted trees, the subtrees of the root; the roots of these subtrees are the *children* of the root, which is their *parent*. A node without children is a *leaf*; the others are *internal nodes*. The *subtrees* of a tree are the tree and the subtrees of its subtrees.

**Definition 11.3 (Binary tree, full binary tree).**

The set of *binary trees* is defined inductively: the *empty tree* is a binary tree, and if $\ell$ and $r$ are binary trees and $k$ a key, the node $(\ell, k, r)$, with left [subtree](#def-b1-induction-and-termination-rooted-tree) $\ell$ and right [subtree](#def-b1-induction-and-termination-rooted-tree) $r$, is a binary tree. A binary tree is *full* if every node has either two non-empty [subtrees](#def-b1-induction-and-termination-rooted-tree) or two empty ones.

**Definition 11.4 (Depth, size, height).**

The *depth* of a node is the number of links from the [root](#def-b1-induction-and-termination-rooted-tree) to it. The *size* of a [binary tree](#def-b1-induction-and-termination-binary-tree) is its number of nodes, 0 for the empty tree. Its *height* is the largest depth of its nodes, and $-1$ for the empty tree: by induction, $h(\text{empty}) = -1$ and $h((\ell, k, r)) = 1 + \max(h(\ell), h(r))$.

```python
@dataclass(frozen=True)
class Node:
    left: "Node | None"  # None is the empty tree
    key: int
    right: "Node | None"


def size(t):
    return 0 if t is None else 1 + size(t.left) + size(t.right)


def height(t):
    return -1 if t is None else 1 + max(height(t.left), height(t.right))


def leaves(t):
    if t is None:
        return 0
    if t.left is None and t.right is None:
        return 1
    return leaves(t.left) + leaves(t.right)


def shapes(h):
    """All binary trees of height at most h, keys 0: rule 1 gives the empty
    tree, rule 2 builds a node from two trees already built."""
    if h < 0:
        return [None]
    smaller = shapes(h - 1)
    return [None] + [Node(a, 0, b) for a in smaller for b in smaller]
```

***Listing 11.1.** [Binary trees](#def-b1-induction-and-termination-binary-tree), and every tree of [height](#def-b1-induction-and-termination-height) at most $h$ code/bachelor-1/11-induction-and-termination/listings/inductive.py*

```
$ python inductive.py
size 4 height 2 leaves 2
empty tree: size 0 height -1
height <= -1:   1 trees, largest size  0, 2^(h+1) - 1 =  0
height <=  0:   2 trees, largest size  1, 2^(h+1) - 1 =  1
height <=  1:   5 trees, largest size  3, 2^(h+1) - 1 =  3
height <=  2:  26 trees, largest size  7, 2^(h+1) - 1 =  7
height <=  3: 677 trees, largest size 15, 2^(h+1) - 1 = 15
```

***Output 11.1.** A tree of four nodes, the empty tree, and the trees produced by the rules up to [height](#def-b1-induction-and-termination-height) 3.*

`shapes` applies the rules literally: the trees of [height](#def-b1-induction-and-termination-height) at most $h$ are the empty tree and the nodes built from two trees of [height](#def-b1-induction-and-termination-height) at most $h - 1$, so their number $a_h$ satisfies $a_{-1} = 1$ and $a_h = 1 + a_{h-1}^2$. The convention $-1$ for the empty tree makes this rule, and the bounds below, hold without exceptions.

![The two rules that generate binary trees, and what they produce from trees of height at most 0 (the empty tree, dashed, and the single node). Height -1, 0, 1, 1 and 1; the last tree is full.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-induction-and-termination/fig-1b151600d0c2.svg)

*The two rules that generate [binary trees](#def-b1-induction-and-termination-binary-tree), and what they produce from trees of [height](#def-b1-induction-and-termination-height) at most 0 (the empty tree, dashed, and the single node). [Height](#def-b1-induction-and-termination-height) $-1$, 0, 1, 1 and 1; the last tree is [full](#def-b1-induction-and-termination-binary-tree).*

## 11.2 Structural induction

**Definition 11.5 (Structural induction).**

To prove a property $P$ of every element of an [inductively defined set](#def-b1-induction-and-termination-inductive) by *structural induction*, prove that $P$ holds for the elements given by the base rules, and that each construction rule, applied to elements satisfying $P$, builds an element satisfying $P$.

**Proposition 11.6 (Structural induction is sound).**

If the two parts of a [structural induction](#def-b1-induction-and-termination-structural) are proved, then $P$ holds for every element of the set.

**Proof.** Every element is built by finitely many applications of the rules; call its *rank* the least number of rule applications in such a construction. We prove “$P$ holds for every element of rank at most $n$” by induction on $n \geq 1$. An element of rank 1 comes from a base rule: $P$ holds. An element of rank $n + 1$ comes from a construction rule applied to elements of smaller rank, which satisfy $P$ by the induction hypothesis, so it satisfies $P$. (For [binary trees](#def-b1-induction-and-termination-binary-tree), an induction on the [height](#def-b1-induction-and-termination-height) does the same work.) ∎

**Proposition 11.7 (Size, height and leaves of a binary tree).**

A [binary tree](#def-b1-induction-and-termination-binary-tree) of [height](#def-b1-induction-and-termination-height) $h$ has a [size](#def-b1-induction-and-termination-height) $n$ with $h + 1 \leq n \leq 2^{h + 1} - 1$. A [full](#def-b1-induction-and-termination-binary-tree) non-empty [binary tree](#def-b1-induction-and-termination-binary-tree) has one more [leaf](#def-b1-induction-and-termination-rooted-tree) than [internal nodes](#def-b1-induction-and-termination-rooted-tree).

**Proof.** By [structural induction](#def-b1-induction-and-termination-structural). The empty tree has $h = -1$ and $n = 0 = h + 1 = 2^0 - 1$. For a node with [subtrees](#def-b1-induction-and-termination-rooted-tree) of [heights](#def-b1-induction-and-termination-height) $h_\ell$, $h_r$ and [sizes](#def-b1-induction-and-termination-height) $n_\ell$, $n_r$ satisfying the bounds, $h = 1 + \max(h_\ell, h_r)$ and $n = 1 + n_\ell +
n_r$. The higher [subtree](#def-b1-induction-and-termination-rooted-tree) alone has at least $\max(h_\ell, h_r) + 1 = h$ nodes, so $n \geq h + 1$; and $n \leq 1 +
2(2^{h} - 1) = 2^{h + 1} - 1$, since both [heights](#def-b1-induction-and-termination-height) are at most $h - 1$. For [full](#def-b1-induction-and-termination-binary-tree) trees: a single node has one [leaf](#def-b1-induction-and-termination-rooted-tree) and no [internal node](#def-b1-induction-and-termination-rooted-tree). A node with two non-empty [full](#def-b1-induction-and-termination-binary-tree) [subtrees](#def-b1-induction-and-termination-rooted-tree) having $f_\ell = i_\ell + 1$ and $f_r = i_r + 1$ leaves has $f_\ell + f_r = i_\ell + i_r + 2$ leaves and $i_\ell + i_r + 1$ [internal nodes](#def-b1-induction-and-termination-rooted-tree), itself included. ∎

![The induction step for full trees: each subtree has one more leaf than internal nodes, and the root adds one internal node and no leaf, so the whole tree keeps the difference of one. Leaves are pale, internal nodes shaded.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-induction-and-termination/fig-6bb459d56f27.svg)

*The induction step for [full](#def-b1-induction-and-termination-binary-tree) trees: each [subtree](#def-b1-induction-and-termination-rooted-tree) has one more [leaf](#def-b1-induction-and-termination-rooted-tree) than [internal nodes](#def-b1-induction-and-termination-rooted-tree), and the [root](#def-b1-induction-and-termination-rooted-tree) adds one [internal node](#def-b1-induction-and-termination-rooted-tree) and no [leaf](#def-b1-induction-and-termination-rooted-tree), so the whole tree keeps the difference of one. Leaves are pale, [internal nodes](#def-b1-induction-and-termination-rooted-tree) shaded.*

Lists are proved about in the same way. With the recursive definition $\mathit{rev}([\,]) = [\,]$ and $\mathit{rev}([x] + \ell) = \mathit{rev}(\ell) + [x]$, first prove $\mathit{rev}(\ell + m) = \mathit{rev}(m) +
\mathit{rev}(\ell)$ by induction on $\ell$: for $\ell = [\,]$ both sides are $\mathit{rev}(m)$; and $\mathit{rev}([x] + \ell + m) = \mathit{rev}(\ell + m) + [x] = \mathit{rev}(m) + \mathit{rev}(\ell) + [x] =
\mathit{rev}(m) + \mathit{rev}([x] + \ell)$. Then $\mathit{rev}(\mathit{rev}(\ell)) = \ell$ by induction on $\ell$: $\mathit{rev}(\mathit{rev}([x] + \ell)) = \mathit{rev}(\mathit{rev}(\ell) + [x]) = \mathit{rev}([x]) +
\mathit{rev}(\mathit{rev}(\ell)) = [x] + \ell$.

```python
def rev(xs):
    """rev([]) = [];  rev([x] + rest) = rev(rest) + [x]."""
    return [] if not xs else rev(xs[1:]) + [xs[0]]


if __name__ == "__main__":
    print(rev([1, 2, 3, 4]), rev(rev([1, 2, 3, 4])))
    checked = 0
    for n in range(8):
        for xs in product(range(3), repeat=n):  # every list of length n over {0, 1, 2}
            xs = list(xs)
            assert rev(rev(xs)) == xs
            assert all(rev(xs[:k] + xs[k:]) == rev(xs[k:]) + rev(xs[:k])
                       for k in range(n + 1))
            checked += 1
    print(checked, "lists checked; a check is not a proof: see the induction")
```

***Listing 11.2.** Reverse, and a check on 3280 lists code/bachelor-1/11-induction-and-termination/listings/reverse_twice.py*

```
$ python reverse_twice.py
[4, 3, 2, 1] [1, 2, 3, 4]
3280 lists checked; a check is not a proof: see the induction
```

***Output 11.2.** The check passes; the proof above covers the lists it did not try.*

The first lemma was needed because the property of $\mathit{rev}(\mathit{rev}(\ell))$ alone does not carry through the induction step: proving a stronger or more general statement is often what makes an induction go through.

## 11.3 Well-founded orders

**Definition 11.8 (Strict order, minimal element, immediate predecessor).**

A *strict order* $<$ on a set is irreflexive ($x < x$ never holds) and transitive; from an order $\leq$ one gets the strict order $x < y$ when $x \leq y$ and $x \neq y$. An element $m$ of a subset $S$ is *minimal* in $S$ if no element of $S$ is smaller than $m$. An *immediate predecessor* of $y$ is an $x < y$ with no $z$ such that $x < z < y$.

**Definition 11.9 (Well-founded order).**

A [strict order](#def-b1-induction-and-termination-strict-order) is *well-founded* if there is no infinite strictly descending chain $x_0
> x_1 > x_2 > \cdots$.

The natural numbers with $<$ are [well-founded](#def-b1-induction-and-termination-well-founded); the integers are not ($0 > -1 > -2 > \cdots$), nor the non-negative rationals ($1 > 1/2 > 1/4 > \cdots$). Proper [subtrees](#def-b1-induction-and-termination-rooted-tree) of a tree, or the order “is a proper [subformula](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-size) of”, are [well-founded](#def-b1-induction-and-termination-well-founded), since each step down a tree loses at least one node.

**Proposition 11.10 (Two definitions agree).**

A [strict order](#def-b1-induction-and-termination-strict-order) is [well-founded](#def-b1-induction-and-termination-well-founded) if and only if every non-empty subset has a [minimal element](#def-b1-induction-and-termination-strict-order).

**Proof.** If a non-empty set $S$ has no [minimal element](#def-b1-induction-and-termination-strict-order), pick $x_0$ in $S$; it is not [minimal](#def-b1-induction-and-termination-strict-order), so some $x_1 \in S$ is smaller; and so on, which builds an infinite descending chain. Conversely, an infinite descending chain is a non-empty set without [minimal element](#def-b1-induction-and-termination-strict-order): each of its elements has a smaller one after it. ∎

The second form gives *[well-founded](#def-b1-induction-and-termination-well-founded) induction*: if $P(y)$ follows from $P(x)$ for all $x < y$, then $P$ holds everywhere, for otherwise the set of counterexamples would have a [minimal element](#def-b1-induction-and-termination-strict-order) $y$, all of whose smaller elements satisfy $P$, and so would $y$. Induction on $\mathbb{N}$ and [structural induction](#def-b1-induction-and-termination-structural) are the cases of $<$ on numbers and of the “is a proper [subtree](#def-b1-induction-and-termination-rooted-tree) of” order.

**Definition 11.11 (Product order, lexicographic order).**

On pairs of elements of ordered sets $A$ and $B$, the *product order* sets $(a, b) \leq (a',
b')$ when $a \leq a'$ and $b \leq b'$; the *lexicographic order* sets $(a, b) < (a', b')$ when $a < a'$, or $a = a'$ and $b < b'$. Both extend to tuples of a fixed length $k$, the lexicographic order comparing the first component where two tuples differ.

**Proposition 11.12 (Lexicographic order is well-founded).**

If $<_A$ and $<_B$ are [well-founded](#def-b1-induction-and-termination-well-founded), the [lexicographic order](#def-b1-induction-and-termination-lex) on $A \times B$ is [well-founded](#def-b1-induction-and-termination-well-founded), and so is the strict [product order](#def-b1-induction-and-termination-lex). By induction, so are both orders on $k$-tuples.

**Proof.** Take a descending chain $(a_0, b_0) > (a_1, b_1) > \cdots$. Along it, $a_0 \geq a_1 \geq \cdots$, since each step either decreases $a$ or keeps it. As $A$ is [well-founded](#def-b1-induction-and-termination-well-founded), $a$ decreases only finitely many times: from some index on, $a$ is constant, and then $b$ decreases at every step, which can happen only finitely often in $B$. So the chain is finite. A strict decrease in the [product order](#def-b1-induction-and-termination-lex) is a decrease in the [lexicographic order](#def-b1-induction-and-termination-lex), so the [product order](#def-b1-induction-and-termination-lex) has no infinite chain either. For $k$-tuples, write $A_1 \times \dots \times A_k$ as $A_1 \times (A_2 \times \dots \times A_k)$. ∎

![A descending chain in the lexicographic order on N2 from (4, 1). A step may jump upwards in j, without bound, but only by lowering i: the chain is finite, although no bound on its length can be given in advance.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-induction-and-termination/fig-45706b496388.svg)

*A descending chain in the [lexicographic order](#def-b1-induction-and-termination-lex) on $\mathbb{N}^2$ from $(4, 1)$. A step may jump upwards in $j$, without bound, but only by lowering $i$: the chain is finite, although no bound on its length can be given in advance.*

The [lexicographic order](#def-b1-induction-and-termination-lex) on $\mathbb{N}^2$ shows why well-foundedness is more than “the values stay positive”: the pair $(1, 0)$ has infinitely many smaller elements $(0, j)$, and no [immediate predecessor](#def-b1-induction-and-termination-strict-order), yet every descending chain is finite. A directed graph whose arcs all go from a larger to a smaller element has no cycle; the converse view, the order of reachability in a directed acyclic graph, returns with graphs in [Chapter 24](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#ch-b1-graph-traversals).

## 11.4 Termination by a variant

**Definition 11.13 (Termination, variant).**

A loop or a recursive function *terminates* if every execution reaches its end after finitely many steps. A *variant* is a function from the states of the loop (or the arguments of the function) to a set with a [well-founded order](#def-b1-induction-and-termination-well-founded) that strictly decreases at each iteration (or at each recursive call). A loop with a variant terminates: otherwise the values of the variant would form an infinite descending chain.

Euclid’s algorithm, which replaces $(a, b)$ by $(b, a \bmod b)$ while $b > 0$, has the [variant](#def-b1-induction-and-termination-variant) $b$ in $\mathbb{N}$: $a \bmod b < b$. A [variant](#def-b1-induction-and-termination-variant) need not be a number. The loop below has none in $\mathbb{N}$, since it sometimes increases $j$, but the pair $(i, j)$ decreases in the [lexicographic order](#def-b1-induction-and-termination-lex) at every step.

```python
i, j = 3, 0
steps = 0
while i > 0 or j > 0:
    print(f"step {steps:2d}: variant (i, j) = ({i}, {j})")
    if j > 0:
        j -= 1  # (i, j) > (i, j - 1)
    else:
        i, j = i - 1, 2 * i  # (i, 0) > (i - 1, anything): j may grow
    steps += 1
print(f"stopped after {steps} steps at ({i}, {j})")
```

***Listing 11.3.** A loop with a lexicographic [variant](#def-b1-induction-and-termination-variant) code/bachelor-1/11-induction-and-termination/listings/lex_loop.py*

```
$ python lex_loop.py
step  0: variant (i, j) = (3, 0)
step  1: variant (i, j) = (2, 6)
step  2: variant (i, j) = (2, 5)
step  3: variant (i, j) = (2, 4)
step 12: variant (i, j) = (1, 0)
step 13: variant (i, j) = (0, 2)
step 14: variant (i, j) = (0, 1)
stopped after 15 steps at (0, 0)
```

***Output 11.3.** The [variant](#def-b1-induction-and-termination-variant) at each step (the middle steps are left out). Some lines are left out.*

Ackermann’s function, named after the mathematician Wilhelm Ackermann, [terminates](#def-b1-induction-and-termination-variant) for the same reason, although it calls itself on an argument that is the result of another call.

```python
def ack(m, n):
    global calls
    calls += 1
    if m == 0:
        return n + 1
    if n == 0:
        return ack(m - 1, 1)
    return ack(m - 1, ack(m, n - 1))
```

***Listing 11.4.** Ackermann’s function code/bachelor-1/11-induction-and-termination/listings/ackermann.py*

```
$ python ackermann.py
m\n             0             1             2             3             4
  0         1 (1)         2 (1)         3 (1)         4 (1)         5 (1)
  1         2 (2)         3 (4)         4 (6)         5 (8)        6 (10)
  2         3 (5)        5 (14)        7 (27)        9 (44)       11 (65)
  3        5 (15)      13 (106)      29 (541)     61 (2432)   125 (10307)
```

***Output 11.4.** Values, and calls in parentheses: the third row already doubles at each step.*

**Proposition 11.14 (Ackermann’s function terminates).**

For all natural numbers $m$ and $n$, the call $\mathit{ack}(m, n)$ [terminates](#def-b1-induction-and-termination-variant).

**Proof.** By [well-founded](#def-b1-induction-and-termination-well-founded) induction on $(m, n)$ in the [lexicographic order](#def-b1-induction-and-termination-lex) of $\mathbb{N}^2$. Suppose every call on a smaller pair [terminates](#def-b1-induction-and-termination-variant). If $m = 0$, there is no call. If $n = 0$, the call is on $(m - 1, 1) < (m, 0)$. Otherwise the inner call is on $(m, n - 1) < (m, n)$ and [terminates](#def-b1-induction-and-termination-variant) with some value $v$; the outer call is on $(m - 1, v) < (m, n)$, whatever $v$ is, and [terminates](#def-b1-induction-and-termination-variant). ∎

[Termination](#def-b1-induction-and-termination-variant) says nothing about speed: $\mathit{ack}(4, 2)$ has 19 729 decimal digits, and its call count is beyond reach. The third row is $2^{n + 3} - 3$, which the test checks.

## 11.5 Recursive functions proved correct

```python
def merge(xs, ys):
    if not xs:
        return ys
    if not ys:
        return xs
    if xs[0] <= ys[0]:
        return [xs[0]] + merge(xs[1:], ys)  # the variant drops by one
    return [ys[0]] + merge(xs, ys[1:])  # here too
```

***Listing 11.5.** Merging two sorted lists code/bachelor-1/11-induction-and-termination/listings/merge.py*

```
$ python merge.py
[1, 2, 3, 4, 4, 4, 9, 10, 11]
[5, 6] [7]
```

***Output 11.5.** Two sorted lists merged, and the base cases.*

**Proposition 11.15 (Merge is correct).**

If $xs$ and $ys$ are sorted, $\mathit{merge}(xs, ys)$ [terminates](#def-b1-induction-and-termination-variant) and returns a sorted list holding the elements of both, with their multiplicities.

**Proof.** [Termination](#def-b1-induction-and-termination-variant): $\text{len}(xs) + \text{len}(ys)$ is a [variant](#def-b1-induction-and-termination-variant), since each call removes one element. Correctness, by induction on the same quantity: if one list is empty, the other is returned, sorted. Otherwise, say $xs[0] \leq
ys[0]$. By induction, the recursive call returns a sorted list of the elements of $xs[1{:}]$ and $ys$; each of them is at least $xs[0]$, since $xs$ is sorted and $ys[0] \geq xs[0]$. Putting $xs[0]$ in front keeps the list sorted, and adds the one missing element. The other case is symmetric. ∎

**Definition 11.16 (Left-child right-sibling representation).**

The *left-child right-sibling representation* stores a tree of any arity as a [binary tree](#def-b1-induction-and-termination-binary-tree) with the same nodes: the left [subtree](#def-b1-induction-and-termination-rooted-tree) of a node is its first child, and its right [subtree](#def-b1-induction-and-termination-rooted-tree) is its next sibling.

```python
class Tree:  # a node of any arity: a key and a list of children
    key: int
    children: list = field(default_factory=list)


def to_binary(t, siblings=()):
    """t and its younger siblings as one binary tree: left = first child of t,
    right = the next sibling of t."""
    first = to_binary(t.children[0], t.children[1:]) if t.children else None
    nxt = to_binary(siblings[0], siblings[1:]) if siblings else None
    return Node(first, t.key, nxt)


def from_binary(b):
    """The inverse: the list of trees that b and its right spine encode."""
    trees = []
    while b is not None:
        trees.append(Tree(b.key, from_binary(b.left)))
        b = b.right
    return trees


def show(b):
    return "." if b is None else f"({show(b.left)} {b.key} {show(b.right)})"
```

***Listing 11.6.** From any arity to binary, and back code/bachelor-1/11-induction-and-termination/listings/lcrs.py*

```
$ python lcrs.py
binary tree: ((. 2 ((. 6 (. 7 .)) 3 (. 4 ((. 8 .) 5 .)))) 1 .)
back again equal: True
```

***Output 11.6.** The tree of the figure below as a [binary tree](#def-b1-induction-and-termination-binary-tree) (`.` is the empty tree), and the round trip.*

![A tree of arity 4 and its left-child right-sibling binary tree. The same eight nodes; the children of a node become a chain of right links starting at its left child.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-induction-and-termination/fig-47ee9f59ea22.svg)

*A tree of arity 4 and its left-child right-sibling [binary tree](#def-b1-induction-and-termination-binary-tree). The same eight nodes; the [children](#def-b1-induction-and-termination-rooted-tree) of a node become a chain of right links starting at its left child.*

The two conversions are inverse to each other, which is proved by [structural induction](#def-b1-induction-and-termination-structural) on trees (and on lists of trees, the two definitions depending on each other); the test checks it on random trees. [Mutually recursive](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-mutual) functions, such as the even and odd test of [Chapter 3](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#ch-b1-c-functions-and-stack), terminate by a common [variant](#def-b1-induction-and-termination-variant): here $n$ decreases at every call, whichever function makes it.

```python
def is_even(n):
    return True if n == 0 else is_odd(n - 1)


def is_odd(n):
    return False if n == 0 else is_even(n - 1)


if __name__ == "__main__":
    print([n for n in range(12) if is_even(n)], is_odd(7))
```

***Listing 11.7.** Even and odd, in Python code/bachelor-1/11-induction-and-termination/listings/even_odd.py*

```
$ python even_odd.py
[0, 2, 4, 6, 8, 10] True
```

***Output 11.7.** The even numbers below 12, and seven is odd.*

## 11.6 Exercises

**Exercise 11.1 ★.**

Give the [size](#def-b1-induction-and-termination-height) and [height](#def-b1-induction-and-termination-height) of: the empty tree; a single node; a node whose left [subtree](#def-b1-induction-and-termination-rooted-tree) is a single node and right [subtree](#def-b1-induction-and-termination-rooted-tree) empty; and the tree `t` of [Output 11.1](#out-b1-induction-and-termination-inductive), `Node(Node(None, 2, None), 5, Node(Node(None, 7, None), 9, None))`.

**Solution of Exercise 11.1.**

Empty tree: [size](#def-b1-induction-and-termination-height) 0, [height](#def-b1-induction-and-termination-height) $-1$. Single node: 1 and 0. A node with a left child only: 2 and 1. The tree `t`: 4 nodes (5, 2, 9, 7), and the longest path 5, 9, 7 has two links: [height](#def-b1-induction-and-termination-height) 2, as [Output 11.1](#out-b1-induction-and-termination-inductive) prints.

**Exercise 11.2 ★.**

Euclid’s algorithm runs on $(252, 105)$. Give the successive values of the [variant](#def-b1-induction-and-termination-variant) $b$, and the result.

**Solution of Exercise 11.2.**

$(252, 105) \to (105, 42) \to (42, 21) \to (21, 0)$: the [variant](#def-b1-induction-and-termination-variant) $b$ takes the values 105, 42, 21 and 0, and the result is 21.

**Exercise 11.3 ★.**

Predict the output of the program.

```python
from lcrs import Tree, show, to_binary

print(show(to_binary(Tree(1, [Tree(2, [Tree(4)]), Tree(3)]))))
print(show(to_binary(Tree(1, [Tree(2), Tree(3), Tree(4)]))))
```

***Listing 11.8.** Two small trees converted code/bachelor-1/11-induction-and-termination/listings/exo_lcrs.py*

**Solution of Exercise 11.3.**

```
(((. 4 .) 2 (. 3 .)) 1 .)
((. 2 (. 3 (. 4 .))) 1 .)
```

***Output 11.9.** The two [binary trees](#def-b1-induction-and-termination-binary-tree). Some lines are left out.*

In the first tree, 2 is the first child of 1 (left of 1), 4 the first child of 2 (left of 2), and 3 the next sibling of 2 (right of 2). In the second, the three [children](#def-b1-induction-and-termination-rooted-tree) of 1 form a chain of right links under the left child 2.

**Exercise 11.4 ★.**

Which [strict orders](#def-b1-induction-and-termination-strict-order) are [well-founded](#def-b1-induction-and-termination-well-founded)? (a) $<$ on the integers greater than $-10$; (b) “divides and is different” on positive integers; (c) “is a proper prefix of” on finite words; (d) $<$ on the real numbers of $[0, 1]$.

**Solution of Exercise 11.4.**

(a) [Well-founded](#def-b1-induction-and-termination-well-founded): a descending chain of integers greater than $-10$ starting at $x_0$ has at most $x_0 + 10$ steps. (b) [Well-founded](#def-b1-induction-and-termination-well-founded): a proper divisor of a positive integer is smaller than it, so a descending chain is a descending chain in $\mathbb{N}$. (c) [Well-founded](#def-b1-induction-and-termination-well-founded): a proper prefix is shorter. (d) Not [well-founded](#def-b1-induction-and-termination-well-founded): $1 > 1/2 > 1/4 > \cdots$.

**Exercise 11.5 ★★.**

A student claims that $n$ is a [variant](#def-b1-induction-and-termination-variant) of `steps`. Show that it is not, prove that the function [terminates](#def-b1-induction-and-termination-variant) for all natural numbers $n$ and $\mathit{step} \in \{0, 1\}$ with a lexicographic [variant](#def-b1-induction-and-termination-variant), and give its result.

```python
def steps(n, step):
    print(f"steps({n}, {step})")
    if n <= 0:
        return 0
    if step == 0:
        return steps(n, 1)  # start moving
    return 1 + steps(n - step, step)


print("result", steps(3, 0))
```

***Listing 11.9.** A recursion with two kinds of call code/bachelor-1/11-induction-and-termination/listings/exo_variant.py*

**Solution of Exercise 11.5.**

```
steps(3, 0)
steps(3, 1)
steps(2, 1)
steps(1, 1)
steps(0, 1)
result 3
```

***Output 11.10.** The calls. Some lines are left out.*

The call `steps(n, 1)` made from `steps(n, 0)` keeps $n$: $n$ is not a [variant](#def-b1-induction-and-termination-variant). The pair $(n, 1 -
\mathit{step})$ is one, in the [lexicographic order](#def-b1-induction-and-termination-lex) of $\mathbb{N}^2$: from $(n, 1)$ to $(n, 0)$ on the first kind of call, from $(n, 0)$ to $(n - 1, 0)$ on the second. By induction along this order, `steps(n, step)` returns $n$ for every natural number $n$.

**Exercise 11.6 ★★.**

A library defines the [height](#def-b1-induction-and-termination-height) of the empty tree as 0. Which statements of [Proposition 11.7](#prop-b1-induction-and-termination-bounds) fail with that convention, and how must they be rewritten?

```python
def height0(t):
    return 0 if t is None else 1 + max(height0(t.left), height0(t.right))


leaf = Node(None, 1, None)
for name, t in [("empty", None), ("leaf", leaf), ("three nodes", Node(leaf, 2, leaf))]:
    h = height0(t)
    print(f"{name:12} height0 {h}  size {size(t)}  size <= 2^(h+1) - 1: "
          f"{size(t) <= 2 ** (h + 1) - 1}  size >= h + 1: {size(t) >= h + 1}")
```

***Listing 11.10.** Another [height](#def-b1-induction-and-termination-height) code/bachelor-1/11-induction-and-termination/listings/exo_height0.py*

**Solution of Exercise 11.6.**

```
empty        height0 0  size 0  size <= 2^(h+1) - 1: True  size >= h + 1: False
leaf         height0 1  size 1  size <= 2^(h+1) - 1: True  size >= h + 1: False
three nodes  height0 2  size 3  size <= 2^(h+1) - 1: True  size >= h + 1: True
```

***Output 11.11.** The two conventions compared. Some lines are left out.*

With that convention every [height](#def-b1-induction-and-termination-height) is one more, $h' = h + 1$. The bound $n \leq 2^{h + 1} - 1$ still holds but is no longer reached; $n \geq h + 1$ fails, for the empty tree and for a single node. Rewritten: $h' \leq n \leq 2^{h'} - 1$, and at most $2^{h' - 1}$ leaves ([Exercise 11.9](#exo-b1-induction-and-termination-9)).

**Exercise 11.7 ★★.**

Write `count_paths(t)`, the number of paths from the [root](#def-b1-induction-and-termination-rooted-tree) of a [binary tree](#def-b1-induction-and-termination-binary-tree) to a [leaf](#def-b1-induction-and-termination-rooted-tree), by recursion on the tree. Prove by [structural induction](#def-b1-induction-and-termination-structural) that it equals the number of leaves, and give its value on a [full](#def-b1-induction-and-termination-binary-tree) tree with $i$ [internal nodes](#def-b1-induction-and-termination-rooted-tree).

**Solution of Exercise 11.7.**

```python
def count_paths(t):
    if t is None:
        return 0
    if t.left is None and t.right is None:
        return 1  # the path made of the leaf alone
    return count_paths(t.left) + count_paths(t.right)
```

*Paths from the [root](#def-b1-induction-and-termination-rooted-tree) to a [leaf](#def-b1-induction-and-termination-rooted-tree) code/bachelor-1/11-induction-and-termination/exercises/count_paths.py*

By [structural induction](#def-b1-induction-and-termination-structural): the empty tree has no path and no [leaf](#def-b1-induction-and-termination-rooted-tree); a single node has one path and one [leaf](#def-b1-induction-and-termination-rooted-tree); otherwise a path from the [root](#def-b1-induction-and-termination-rooted-tree) to a [leaf](#def-b1-induction-and-termination-rooted-tree) goes into exactly one of the two [subtrees](#def-b1-induction-and-termination-rooted-tree), and continues as a path from the [root](#def-b1-induction-and-termination-rooted-tree) of that [subtree](#def-b1-induction-and-termination-rooted-tree) to a [leaf](#def-b1-induction-and-termination-rooted-tree) of it, so the counts add, as the leaves do. On a [full](#def-b1-induction-and-termination-binary-tree) tree with $i$ [internal nodes](#def-b1-induction-and-termination-rooted-tree) there are $i + 1$ leaves ([Proposition 11.7](#prop-b1-induction-and-termination-bounds)), hence $i + 1$ paths. The test `tests/test_trees.py` checks both on random trees.

**Exercise 11.8 ★★.**

With $\mathit{flatten}(\text{empty}) = [\,]$ and $\mathit{flatten}((\ell, k, r)) = \mathit{flatten}(\ell) + [k] +
\mathit{flatten}(r)$, prove $\text{len}(\mathit{flatten}(t)) = \text{size}(t)$ by [structural induction](#def-b1-induction-and-termination-structural).

**Solution of Exercise 11.8.**

Empty tree: $\text{len}([\,]) = 0 = \text{size}$. Node $(\ell, k, r)$: $\text{len}(\mathit{flatten}(\ell) + [k] +
\mathit{flatten}(r)) = \text{len}(\mathit{flatten}(\ell)) + 1 + \text{len}(\mathit{flatten}(r)) = \text{size}(\ell) + 1 +
\text{size}(r)$ by the induction hypothesis, which is the [size](#def-b1-induction-and-termination-height) of the node.

**Exercise 11.9 ★★.**

Prove that a non-empty [binary tree](#def-b1-induction-and-termination-binary-tree) of [height](#def-b1-induction-and-termination-height) $h$ has at most $2^h$ leaves. Which trees reach the bound?

**Solution of Exercise 11.9.**

By [structural induction](#def-b1-induction-and-termination-structural) on non-empty trees. A single node: [height](#def-b1-induction-and-termination-height) 0, one [leaf](#def-b1-induction-and-termination-rooted-tree), $2^0 = 1$. A node with one empty [subtree](#def-b1-induction-and-termination-rooted-tree): its leaves are those of the other [subtree](#def-b1-induction-and-termination-rooted-tree), of [height](#def-b1-induction-and-termination-height) $h - 1$, so at most $2^{h - 1} \leq 2^h$. A node with two non-empty [subtrees](#def-b1-induction-and-termination-rooted-tree) of [heights](#def-b1-induction-and-termination-height) at most $h - 1$: at most $2^{h - 1} + 2^{h - 1} = 2^h$ leaves. The bound is reached exactly by the *perfect* trees, in which every [internal node](#def-b1-induction-and-termination-rooted-tree) has two [children](#def-b1-induction-and-termination-rooted-tree) and every [leaf](#def-b1-induction-and-termination-rooted-tree) has [depth](#def-b1-induction-and-termination-height) $h$.

**Exercise 11.10 ★★★.**

On the finite words over a finite alphabet, the *shortlex* order compares lengths first and, between words of the same length, uses the dictionary order. Prove that it is [well-founded](#def-b1-induction-and-termination-well-founded). Show that the dictionary order alone, on the words over $\{a, b\}$, is not.

**Solution of Exercise 11.10.**

In a descending chain for shortlex, the lengths never increase, so from some point on they are constant, equal to some $L$ (lengths are natural numbers). From then on the chain is strictly descending among the words of length $L$, of which there are finitely many: it is finite. For the dictionary order, $b > ab > aab > aaab > \cdots$: at each step the first letters compare $a < b$ at the first difference, and the chain never ends.

**Exercise 11.11 ★★★.**

In the sorting game, a move swaps two adjacent numbers of a list that are out of order. Prove that every game ends, with a [variant](#def-b1-induction-and-termination-variant), that it ends on the sorted list, and that the number of moves does not depend on the choices. Write the game and test the claims.

**Solution of Exercise 11.11.**

```python
"""sort_game.py: swap two adjacent numbers that are out of order, until none is.

The variant is the number of inversions, pairs i < j with xs[i] > xs[j]: a swap
of an adjacent inverted pair removes exactly that inversion and changes no other."""


def inversions(xs):
    return sum(xs[i] > xs[j] for i in range(len(xs)) for j in range(i + 1, len(xs)))


def play(xs, choose=min):
    """Play until sorted; choose picks among the positions of inverted pairs."""
    xs, moves = list(xs), 0
    while True:
        out_of_order = [i for i in range(len(xs) - 1) if xs[i] > xs[i + 1]]
        if not out_of_order:
            return xs, moves
        i = choose(out_of_order)
        xs[i], xs[i + 1] = xs[i + 1], xs[i]
        moves += 1
```

*The sorting game code/bachelor-1/11-induction-and-termination/exercises/sort_game.py*

A swap of an adjacent inverted pair $x_i > x_{i+1}$ removes that inversion; every other pair keeps its two elements, in the same order, so the number of inversions decreases by exactly one. It is a [variant](#def-b1-induction-and-termination-variant) in $\mathbb{N}$, so every game ends. It ends when no adjacent pair is inverted, that is when the list is sorted; and it takes exactly as many moves as the starting list has inversions, whatever the choices. The test plays with the leftmost and the rightmost choice and checks the result and the count on random lists.

**Exercise 11.12 ★★★.**

McCarthy’s 91 function is $f(n) = n - 10$ if $n > 100$, and $f(n) = f(f(n + 11))$ otherwise. Prove that $f(n) = 91$ for every integer $n \leq 100$, by [well-founded](#def-b1-induction-and-termination-well-founded) induction on $101 - n$ (with a separate argument for $90 \leq n \leq 100$), and deduce that $f$ [terminates](#def-b1-induction-and-termination-variant) on every integer.

**Solution of Exercise 11.12.**

Use [well-founded](#def-b1-induction-and-termination-well-founded) induction on $m = 101 - n \geq 1$ for $n \leq 100$, proving that $f(n)$ [terminates](#def-b1-induction-and-termination-variant) with value 91. First, if $90 \leq n \leq 100$, then $n + 11 > 100$, so $f(n + 11) = n + 1$ and $f(n) = f(n + 1)$; with $f(101) = 91$, going down from 100 to 90 gives $f(n) = 91$. If $n < 90$, then $n + 11 \leq 100$ and $101 - (n + 11) < m$, so by induction $f(n + 11)$ [terminates](#def-b1-induction-and-termination-variant) with 91, and $f(n) = f(91) = 91$ by the first case. For $n > 100$ the function returns at once. The test checks the values from $-50$ to 200.

## 11.7 Problem: The game that always ends

**Problem 11.1.**

Weekend problem — The game that always ends

A position is a list of natural numbers. A move picks an entry $k > 0$ and replaces it by two entries $k - 1$; the play ends when every entry is 0. From $(2)$ one may play $(2) \to (1, 1) \to (0, 0, 1) \to (0, 0, 0, 0)$, or replace the other 1 first. The program lists the possible lengths of all plays from a few positions, and counts the plays.

```python
def moves(state):
    """Every state one move away; a state is a tuple of natural numbers."""
    return [state[:i] + (k - 1, k - 1) + state[i + 1:]
            for i, k in enumerate(state) if k > 0]


@cache
def lengths(state):
    """The set of lengths of all plays from state."""
    nxt = moves(state)
    if not nxt:
        return frozenset([0])
    return frozenset(1 + n for s in nxt for n in lengths(s))


@cache
def plays(state):
    """The number of different plays from state."""
    nxt = moves(state)
    return 1 if not nxt else sum(plays(s) for s in nxt)


def potential(state):
    return sum(2 ** a - 1 for a in state)

```

***Listing 11.11.** The game, its plays and their lengths code/bachelor-1/11-induction-and-termination/listings/game.py*

```
$ python game.py
start        potential  play lengths        plays
(1,)                 1           [1]            1
(2,)                 3           [3]            2
(3,)                 7           [7]           80
(4,)                15          [15]     21964800
(1, 2)               4           [4]            8
(2, 2, 1)            7           [7]          560
(3, 1, 0)            8           [8]          640
(3, 3)              14          [14]     21964800
```

***Output 11.8.** One length per position, whatever the choices, among up to 21 964 800 different plays.*

**Part I — Positions and plays as data.**

1. Define the set of plays inductively: a play from a position $s$ is either $s$ alone, if no move is possible, or $s$ followed by a play from a position one move away.
2. List the two plays from $(2)$ and the two from $(1, 1)$ .
3. Why does `plays((4,))` equal `plays((3, 3))` ?
4. Explain the recursion of `lengths` , and why its base case returns $\{0\}$ .
5. Why is `@cache` needed to count 21 964 800 plays?
6. Does the order of the entries in a position matter for the lengths? For the number of plays?

**Part II — Termination.**

7. Show that the sum of the entries is not a [variant](#def-b1-induction-and-termination-variant) , nor the number of entries, nor the largest entry.
8. Let $K$ be the largest entry of the starting position. Show that no entry ever exceeds $K$ .
9. For a position $s$ , let $c(s) = (c_K, c_{K-1}, \dots, c_0)$ , where $c_j$ is the number of entries equal to $j$ . Show that a move decreases $c(s)$ in the [lexicographic order](#def-b1-induction-and-termination-lex) of $\mathbb{N}^{K+1}$ .
10. Deduce from [Proposition 11.12](#prop-b1-induction-and-termination-lex) that every play is finite.
11. Is $c$ a [variant](#def-b1-induction-and-termination-variant) in the [product order](#def-b1-induction-and-termination-lex) ? Why does that not matter?
12. Could a play from $(3, 1, 0)$ be longer than 1000 moves? Answer from Part II alone, then from the table.

**Part III — A single entry.**

13. Let $M(k)$ be the number of moves of a play from $(k)$ , assuming it does not depend on the choices. Show $M(0) = 0$ and $M(k) = 1 + 2M(k - 1)$ .
14. Deduce $M(k) = 2^k - 1$ by induction, and compare with the table.
15. In a play from $(k)$ , the two copies of $k - 1$ evolve independently. Make this precise: a play from a position is an interleaving of plays from its entries.
16. Deduce that a play from $(a_1, \dots, a_n)$ makes $\sum_i (2^{a_i} - 1)$ moves, if each single-entry play has a fixed length.
17. Where did Part III assume what it set out to prove? Why does the interleaving argument still need the single-entry result as an induction hypothesis?
18. Give the number of plays from $(2)$ , $(3)$ and $(1, 2)$ from the table, and check $(2)$ and $(1, 2)$ by hand.

**Part IV — A potential.**

19. Let $\Phi(s) = \sum_i (2^{a_i} - 1)$ . Compute the change of $\Phi$ in a move that replaces $k$ by two copies of $k - 1$ .
20. Show that $\Phi(s) \geq 0$ , with equality exactly when the play has ended.
21. Deduce that every play from $s$ has exactly $\Phi(s)$ moves.
22. Compare this proof with that of Part II: which one gives [termination](#def-b1-induction-and-termination-variant) , which one the length, and why is $\Phi$ a [variant](#def-b1-induction-and-termination-variant) in $\mathbb{N}$ although the sum of entries was not?
23. The program checks the result on every position of at most three entries below 4. What does that check add to the proof, and what does the proof add to the check?
24. State the named result: *every play from $(a_1, \dots, a_n)$ has the same length $\sum_i (2^{a_i} - 1)$* .

**Solution of Problem 11.1.**

**1.** The base rule: a position with no entry above 0 is a play by itself. The construction rule: if $s'$ is one move away from $s$ and $p$ is a play from $s'$, then $s$ followed by $p$ is a play from $s$.

**2.** From $(2)$: $(2), (1, 1), (0, 0, 1), (0, 0, 0, 0)$ and $(2), (1, 1), (1, 0, 0), (0, 0, 0, 0)$. From $(1, 1)$: the same two without their first position.

**3.** The only move from $(4)$ leads to $(3, 3)$, so every play from $(4)$ is $(4)$ followed by a play from $(3, 3)$.

**4.** It follows the inductive definition of plays: a final position has one play, of length 0; otherwise the lengths are one more than those of the plays from each position one move away.

**5.** The same position is reached by many orders of moves; without the cache, `plays` would recompute it each time, and the count would cost as many calls as there are plays, 21 964 800. With the cache, each position is computed once.

**6.** No: exchanging entries exchanges the moves, and gives a one-to-one correspondence between the plays of the two positions, which preserves lengths. The number of plays is the same too.

**7.** The sum changes by $2(k - 1) - k = k - 2$, which is positive for $k \geq 3$: $(3) \to (2, 2)$ raises it from 3 to 4. The number of entries grows by one at each move. The largest entry can stay the same: $(2, 2) \to (1, 1, 2)$.

**8.** A move adds only entries $k - 1$, smaller than an existing entry.

**9.** The move lowers $c_k$ by one and raises $c_{k - 1}$ by two, leaving the others. The first component where the vectors differ is $c_k$, which decreased.

**10.** The [lexicographic order](#def-b1-induction-and-termination-lex) on $\mathbb{N}^{K + 1}$ is [well-founded](#def-b1-induction-and-termination-well-founded), and a play gives a descending chain of vectors $c(s)$: it is finite.

**11.** No: $c_{k - 1}$ increases, so the new vector is not below the old in the [product order](#def-b1-induction-and-termination-lex). Only the existence of a [well-founded order](#def-b1-induction-and-termination-well-founded) in which $c$ decreases matters.

**12.** Part II proves that every play is finite but gives no bound: a lexicographic chain can be as long as one likes. The table says that every play from $(3, 1, 0)$ has 8 moves.

**13.** From $(0)$ no move is possible. From $(k)$ the first move gives $(k - 1, k - 1)$, and each copy then needs $M(k - 1)$ moves of its own: $M(k) = 1 + 2M(k - 1)$.

**14.** $M(0) = 0 = 2^0 - 1$, and $1 + 2(2^{k - 1} - 1) = 2^k - 1$. The table: 1, 3, 7, 15 for $k = 1, \dots, 4$.

**15.** Each move acts on one entry, and the entries it creates descend from it. Restricted to the descendants of entry $i$, the moves of a play form a play from $(a_i)$, and the whole play interleaves these $n$ plays.

**16.** The moves of the whole play are the moves of the $n$ sub-plays: $\sum_i M(a_i) = \sum_i (2^{a_i} - 1)$.

**17.** Question 13 assumed that $M(k - 1)$ is well defined. The proof is an induction on $k$: assuming every play from $(k - 1)$ has $2^{k - 1} - 1$ moves, question 15 applied to $(k - 1, k - 1)$ shows that every play from $(k)$ has $1 + 2(2^{k - 1} - 1)$ moves.

**18.** 2, 80 and 8. From $(1, 2)$: the play from $(2)$ has 3 moves, in 2 orders, and the single move of $(1)$ can come in any of 4 places among them: $4 \times 2 = 8$.

**19.** $-(2^k - 1) + 2(2^{k - 1} - 1) = -2^k + 1 + 2^k - 2 = -1$.

**20.** Each term $2^{a_i} - 1$ is at least 0, and 0 only for $a_i = 0$; so $\Phi(s) = 0$ exactly when every entry is 0, when no move is possible.

**21.** Each move lowers $\Phi$ by exactly one, and the play ends exactly when $\Phi$ reaches 0: a play from $s$ has $\Phi(s)$ moves, which also proves [termination](#def-b1-induction-and-termination-variant) again.

**22.** Part II gives [termination](#def-b1-induction-and-termination-variant) and nothing more; $\Phi$ gives both, because it decreases by exactly one. The sum weighs an entry $k$ by $k$, less than the two entries $k - 1$ can weigh; $\Phi$ weighs it by $2^k - 1$, exactly the cost of the play it will start, so that the move pays one and leaves the rest to the copies.

**23.** The check covers 84 positions exhaustively, and would have caught an error in the program, or a wrong formula; the proof covers every position, of any length and any entries, which no check can enumerate.

**24.** *Every play from $(a_1, \dots, a_n)$ has the same length $\sum_i (2^{a_i} - 1)$*: each move lowers the potential $\Phi$ by exactly one, and the play ends exactly when $\Phi$ is 0. The table and the test confirm it on all the positions they try, from $(1)$ with 1 move to $(4)$ and $(3, 3)$, whose 21 964 800 plays all have 15 and 14 moves.
