---
title: "Proving Algorithms Correct"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 16
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/16-proving-algorithms-correct
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 16 — Proving Algorithms Correct

A binary search passes every one of its ten tests. The next day, asked for a number that is not in the list, it never answers: the program runs until someone stops it. The tests were not wrong; they were too few, as tests always are. A test checks one input. To be sure of all the inputs, one needs an argument.

This chapter gives the two arguments that settle most loops. The first shows that a loop stops; the second, that what it computes is right. Both are short, both can be checked in the code itself with `assert`, and together they find the bug of the binary search above, and others like it, before any test does.

**You already know.**

A `while` loop repeats its body as long as its condition is true (Book 1, grade 6). Linear search looks at each element in turn; binary search halves a sorted list at each step; selection sort and insertion sort put a list in order (Book 1, grade 8). A specification states what a function needs and what it promises, and an assertion stops the program if a condition is false (chapter [1](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#ch-g10-specifications-and-tests)). Euclid’s algorithm finds the greatest common divisor of two numbers by repeated remainders (mathematics, grade 9).

## 16.1 Does it stop?

A `for` loop over a list stops: it has as many turns as the list has elements. A `while` loop stops only if its condition becomes false, and nothing guarantees that it will.

**Definition 16.1 (Variant, termination).**

An algorithm has the property of *termination* if it stops on every input that meets its [precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post). A *variant* of a loop is a whole number, computed from the variables, that is never negative while the loop runs and that strictly decreases at each turn.

A loop with a [variant](#def-g11-proving-algorithms-correct-variant) stops: a whole number that is at least $0$ and loses at least $1$ at each turn cannot do so more times than its first value. Euclid’s algorithm is an example. Its [variant](#def-g11-proving-algorithms-correct-variant) is $b$: the new $b$ is the remainder `a % b`, which is smaller than $b$ and never negative.

```python
def gcd(a, b):
    """Euclid; pre: a >= 0, b >= 0. Variant: b, a whole number that decreases."""
    turn = 0
    while b != 0:
        print(f"turn {turn:2}: a={a:4} b={b:4}")
        a, b = b, a % b       # the new b is a % b, which is smaller than b
        turn = turn + 1
    print(f"turn {turn:2}: a={a:4} b={b:4}  -> b = 0, the loop stops")
    return a


print("gcd =", gcd(1071, 462))
print("gcd =", gcd(233, 144))
```

***Listing 16.1.** Euclid’s algorithm, printing its [variant](#def-g11-proving-algorithms-correct-variant) at each turn. code/grade-11/05-proving-algorithms-correct/listings/variant_check.py*

```
$ python variant_check.py
turn  0: a=1071 b= 462
turn  1: a= 462 b= 147
turn  2: a= 147 b=  21
turn  3: a=  21 b=   0  -> b = 0, the loop stops
gcd = 21
turn  0: a= 233 b= 144
turn  1: a= 144 b=  89
turn  2: a=  89 b=  55
turn  3: a=  55 b=  34
turn  4: a=  34 b=  21
turn  5: a=  21 b=  13
turn  6: a=  13 b=   8
turn  7: a=   8 b=   5
turn  8: a=   5 b=   3
turn  9: a=   3 b=   2
turn 10: a=   2 b=   1
turn 11: a=   1 b=   0  -> b = 0, the loop stops
gcd = 1
```

***Output 16.1.** The [variant](#def-g11-proving-algorithms-correct-variant) $b$ falls at each turn and the loop stops when it reaches $0$: three turns, then eleven (the last line of each run is printed after the loop).*

![The variant of gcd(233, 144), from the run above: a staircase that only goes down, one step per turn, and cannot go below 0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-proving-algorithms-correct/fig-3a4230913529.svg)

*The [variant](#def-g11-proving-algorithms-correct-variant) of `gcd(233, 144)`, from the run above: a staircase that only goes down, one step per turn, and cannot go below $0$.*

The [variant](#def-g11-proving-algorithms-correct-variant) does not have to fall by $1$ each turn; it may fall by much more. What matters is that it falls by at least $1$ and starts from a finite value, which bounds the number of turns.

## 16.2 Is the answer right?

**Definition 16.2 (Correct algorithm).**

An algorithm is *correct* with respect to a specification if, on every input that meets the [precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post), it stops and its result meets the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post).

**Definition 16.3 (Loop invariant).**

A *loop invariant* is a statement about the variables that is true before the first turn of a loop and that each turn keeps true: if it holds at the start of a turn, it holds at the end.

An invariant is then true when the loop stops, together with the negation of the loop’s condition. A good invariant is chosen so that these two facts, put together, give the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post).

**Method 16.4 (Proving a loop with an invariant).**

1. Write the invariant, often “the part already handled is right”, with the loop’s index.
2. **Start** : show that it is true before the first turn.
3. **Keep** : suppose it is true at the start of a turn; show that it is still true after the turn.
4. **End** : add the fact that the loop’s condition is false; deduce the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) .
5. Give a [variant](#def-g11-proving-algorithms-correct-variant) , to show that the end is reached.

The function `largest` returns the largest element of a list. Its invariant is “`best` is the largest of `t[:i]`”. Start: with `i = 1`, `t[:1]` holds only `t[0]`, which is `best`. Keep: if `t[i]` is larger than `best`, it becomes `best`, otherwise `best` stays; either way it is the largest of `t[:i + 1]`, and `i` grows by one. End: the loop stops when `i` equals `len(t)`, so `t[:i]` is the whole list. [Variant](#def-g11-proving-algorithms-correct-variant): `len(t) - i`.

```python
def largest(t):
    """Pre: t is a non-empty list of numbers. Post: returns the largest element of t."""
    best = t[0]
    i = 1
    while i < len(t):
        assert best == max(t[:i])           # invariant: best is the largest of t[:i]
        if t[i] > best:
            best = t[i]
        i = i + 1
    assert i == len(t) and best == max(t)   # at the end: i == len(t), so t[:i] is t
    return best


print(largest([31, 7, 58, 12, 58, 3]))
print(largest([-4]))
```

***Listing 16.2.** The largest element, with its invariant written as an assertion. code/grade-11/05-proving-algorithms-correct/listings/largest.py*

```
$ python largest.py
58
-4
```

***Output 16.2.** No assertion fails on these two lists.*

An assertion of the invariant does not prove it; it checks it on the inputs that are run, and stops the program at the first turn where it fails, which points at the bug. The proof covers all the inputs; the assertion catches the gap between the proof and the code.

## 16.3 Selection sort

Selection sort finds a smallest element of the part not yet sorted and swaps it to the front of that part. Its invariant has two halves: `t[:i]` is sorted, and no element of `t[:i]` is larger than an element of `t[i:]`.

```python
def check(t, i):
    """The invariant: t[:i] is sorted, and nothing in t[:i] is larger than t[i:]."""
    assert all(t[k] <= t[k + 1] for k in range(i - 1))
    assert i == 0 or i == len(t) or t[i - 1] <= min(t[i:])


def selection_sort(t):
    for i in range(len(t)):
        check(t, i)
        m = i                       # find the index m of a smallest element of t[i:]
        for j in range(i + 1, len(t)):
            if t[j] < t[m]:
                m = j
        t[i], t[m] = t[m], t[i]     # move it to place i
        print(f"turn {i}: {t[:i + 1]} | {t[i + 1:]}")
    check(t, len(t))


selection_sort([29, 12, 47, 3, 18, 12])
```

***Listing 16.3.** Selection sort, checking both halves of its invariant. code/grade-11/05-proving-algorithms-correct/listings/selection_sort.py*

```
$ python selection_sort.py
turn 0: [3] | [12, 47, 29, 18, 12]
turn 1: [3, 12] | [47, 29, 18, 12]
turn 2: [3, 12, 12] | [29, 18, 47]
turn 3: [3, 12, 12, 18] | [29, 47]
turn 4: [3, 12, 12, 18, 29] | [47]
turn 5: [3, 12, 12, 18, 29, 47] | []
```

***Output 16.3.** The bar separates `t[:i + 1]`, sorted after the turn, from the rest.*

![Selection sort at the start of turn 2: the sorted part, the rest, and the swap that will put a smallest element of the rest in place 2.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-proving-algorithms-correct/fig-9a92494cba76.svg)

*Selection sort at the start of turn $2$: the sorted part, the rest, and the swap that will put a smallest element of the rest in place $2$.*

Start: with `i = 0`, `t[:0]` is empty, and both halves hold. Keep: the turn puts in place `i` a smallest element of `t[i:]`. By the second half, it is at least as large as everything in `t[:i]`, so the first `i + 1` elements are sorted; being a smallest of `t[i:]`, it is no larger than anything left in `t[i + 1:]`. End: with `i = len(t)`, the whole list is sorted. The swap only exchanges two elements, so the list keeps the same elements. [Variant](#def-g11-proving-algorithms-correct-variant) of the outer loop: `len(t) - i`; the inner loop is a `for` loop and stops.

## 16.4 Insertion sort

Insertion sort takes the elements one by one and slides each into place among those before it, which are already sorted. It has two loops, and each has its own invariant.

```python
def insertion_sort(t):
    for i in range(1, len(t)):
        assert all(t[k] <= t[k + 1] for k in range(i - 1))   # outer: t[:i] is sorted
        x = t[i]
        j = i
        while j > 0 and t[j - 1] > x:
            # inner: t[j + 1:i + 1] holds elements larger than x, moved one place right
            t[j] = t[j - 1]
            j = j - 1
        t[j] = x
        print(f"turn {i}: {t[:i + 1]} | {t[i + 1:]}   ({x} went to place {j})")


insertion_sort([29, 12, 47, 3, 18, 12])
```

***Listing 16.4.** Insertion sort, with its outer invariant asserted. code/grade-11/05-proving-algorithms-correct/listings/insertion_sort.py*

```
$ python insertion_sort.py
turn 1: [12, 29] | [47, 3, 18, 12]   (12 went to place 0)
turn 2: [12, 29, 47] | [3, 18, 12]   (47 went to place 2)
turn 3: [3, 12, 29, 47] | [18, 12]   (3 went to place 0)
turn 4: [3, 12, 18, 29, 47] | [12]   (18 went to place 2)
turn 5: [3, 12, 12, 18, 29, 47] | []   (12 went to place 2)
```

***Output 16.4.** After turn $i$, the first $i + 1$ elements are sorted.*

![Turn 4 of insertion sort. The sorted part was 3, 12, 29, 47; the elements larger than x = 18 move one place right, first 47 then 29, and x lands in the gap.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-proving-algorithms-correct/fig-b60c14bc1859.svg)

*Turn $4$ of insertion sort. The sorted part was $3, 12, 29, 47$; the elements larger than $x = 18$ move one place right, first $47$ then $29$, and $x$ lands in the gap.*

The outer invariant is “`t[:i]` is sorted”. The inner invariant, for the `while` loop, is: the elements of `t[j + 1:i + 1]` are larger than $x$, in order, and putting $x$ in place `j` would give the old `t[:i]` with $x$ added. Each inner turn moves one larger element right and lowers `j`; the inner loop stops when `j` is $0$ or when `t[j - 1]` is not larger than $x$. In both cases $x$, written in place `j`, is not smaller than what comes before it and is smaller than what comes after: `t[:i + 1]` is sorted, and the outer invariant is kept. The inner [variant](#def-g11-proving-algorithms-correct-variant) is `j`, the outer one `len(t) - i`.

## 16.5 Binary search

Binary search finds `x` in a sorted list by keeping a window `t[lo:hi]` outside of which `x` cannot be, and halving it.

```python
def search(t, x):
    """Pre: t is sorted. Post: an index i with t[i] == x, or None if x is not in t."""
    lo, hi = 0, len(t)
    while lo < hi:
        # invariant: x is neither in t[:lo] nor in t[hi:]; variant: hi - lo
        mid = (lo + hi) // 2
        print(f"  lo={lo} mid={mid} hi={hi}")
        if t[mid] == x:
            return mid
        if t[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return None


t = [3, 8, 12, 15, 21, 30, 34, 41, 47, 52]
for x in [41, 3, 20]:
    print("search", x)
    print("->", search(t, x))
```

***Listing 16.5.** Binary search, its invariant and its [variant](#def-g11-proving-algorithms-correct-variant). code/grade-11/05-proving-algorithms-correct/listings/binary_search.py*

```
$ python binary_search.py
search 41
  lo=0 mid=5 hi=10
  lo=6 mid=8 hi=10
  lo=6 mid=7 hi=8
-> 7
search 3
  lo=0 mid=5 hi=10
  lo=0 mid=2 hi=5
  lo=0 mid=1 hi=2
  lo=0 mid=0 hi=1
-> 0
search 20
  lo=0 mid=5 hi=10
  lo=0 mid=2 hi=5
  lo=3 mid=4 hi=5
  lo=3 mid=3 hi=4
-> None
```

***Output 16.5.** Three searches. Looking for $20$, the window shrinks to nothing and the answer is `None`.*

![Looking for 41: the grey cells are outside the window, where 41 cannot be; the blue cell is mid. The third mid holds 41.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-proving-algorithms-correct/fig-3dcd44f4fed8.svg)

*Looking for $41$: the grey cells are outside the window, where $41$ cannot be; the blue cell is `mid`. The third `mid` holds $41$.*

The invariant: `x` is neither in `t[:lo]` nor in `t[hi:]`. Start: both are empty. Keep: if `t[mid] < x`, then, the list being sorted, every element of `t[:mid + 1]` is less than `x`, so `lo = mid + 1` keeps the invariant; if `t[mid] > x`, every element of `t[mid:]` is larger, and `hi = mid` keeps it. End: if the loop stops with `lo >= hi`, the window is empty, and by the invariant `x` is nowhere: `None` is right. The [variant](#def-g11-proving-algorithms-correct-variant) is `hi - lo`: `mid` lies in the window, so both `lo = mid + 1` and `hi = mid` make it smaller.

The [variant](#def-g11-proving-algorithms-correct-variant) is where the opening bug hides. Writing `lo = mid` keeps the invariant, but not the [variant](#def-g11-proving-algorithms-correct-variant): when `hi = lo + 1`, `mid` equals `lo`, and `lo = mid` changes nothing.

```python
def search(t, x, cap=50):
    lo, hi = 0, len(t)
    turns = 0
    while lo < hi:
        turns = turns + 1
        if turns > cap:   # a guard for this demonstration only
            raise RuntimeError(f"no end after {cap} turns: lo={lo}, hi={hi}")
        mid = (lo + hi) // 2
        if t[mid] == x:
            return mid
        if t[mid] < x:
            lo = mid      # the bug: mid was already compared
        else:
            hi = mid
    return None


t = [3, 8, 12, 15, 21, 30, 34, 41, 47, 52]
for x in t:
    assert search(t, x) == t.index(x)
print("all", len(t), "tests pass")
try:
    print(search(t, 20))
except RuntimeError as error:
    print("RuntimeError:", error)
```

***Listing 16.6.** The opening bug, with a guard added for the demonstration. code/grade-11/05-proving-algorithms-correct/listings/binary_search_bug.py*

```
$ python binary_search_bug.py
all 10 tests pass
RuntimeError: no end after 50 turns: lo=3, hi=4
```

***Output 16.6.** Every test passes, since each one searches a number of the list; a number not in it makes the window stop shrinking at `lo=3`, `hi=4`.*

**History — Meaning given to programs.**

The idea of attaching statements to the points of a program and proving that each step keeps them true was published by Robert W. Floyd in 1967, for flowcharts. In 1969, C. A. R. Hoare turned it into rules for reasoning about the instructions of a programming language, one rule per kind of instruction, the loop rule resting on an invariant.

## 16.6 Exercises

**Exercise 16.1 ★.**

Write the list `[5, 2, 9, 1, 7]` after the first two turns of selection sort.

**Solution of Exercise 16.1.**

Turn $0$ swaps the smallest, $1$, into place $0$: `[1, 2, 9, 5, 7]`. Turn $1$ finds $2$ already in place $1$: the list stays `[1, 2, 9, 5, 7]`.

**Exercise 16.2 ★.**

Give a [variant](#def-g11-proving-algorithms-correct-variant) of the loop `while n > 0: n = n - 2`, for `n` a whole number, and say why it is one.

**Solution of Exercise 16.2.**

`n` itself, if `n` starts at $0$ or more: it falls by $2$ at each turn, and the loop runs only while `n > 0`, so during the loop it is a whole number at least $1$. (If `n` starts odd, it ends at $-1$; the [variant](#def-g11-proving-algorithms-correct-variant) only has to be non-negative while the loop runs.)

**Exercise 16.3 ★.**

Give the values of `lo`, `mid` and `hi` at each turn when the chapter’s `search` looks for $52$ in the list of the output.

**Solution of Exercise 16.3.**

`lo=0 mid=5 hi=10`: $30 < 52$; `lo=6 mid=8 hi=10`: $47 < 52$; `lo=9 mid=9 hi=10`: found, the answer is $9$.

**Exercise 16.4 ★.**

For the loop `s = 0`, then `for i in range(len(t)): s = s + t[i]`, is the statement “`s` is the sum of `t[:i]`” true before the first turn?

**Solution of Exercise 16.4.**

Yes: before the first turn `i` is $0$ in the statement, `t[:0]` is empty, its sum is $0$, and `s` is $0$.

**Exercise 16.5 ★.**

A student writes `largest` with `for i in range(1, len(t) - 1)`. On `[4, 9, 2, 11]` it returns $9$. Which step of the proof fails?

**Solution of Exercise 16.5.**

The end step. The invariant still holds at each turn, but the loop stops at `i = len(t) - 1`, so it only gives “`best` is the largest of `t[:len(t) - 1]`”: the last element is never looked at, and $11$ is missed.

**Exercise 16.6 ★★.**

Prove that this loop stops for every whole number `n`, by giving a [variant](#def-g11-proving-algorithms-correct-variant): `while n > 1`, if `n` is even, `n = n // 2`, otherwise `n = n - 1`.

**Solution of Exercise 16.6.**

`n` is a [variant](#def-g11-proving-algorithms-correct-variant). Inside the loop `n > 1`; then `n // 2` and `n - 1` are both whole numbers smaller than `n` and at least $1$. So `n` stays non-negative and strictly decreases: the loop stops.

**Exercise 16.7 ★★.**

Write `index_of_min(t, i)` that returns the index of a smallest element of `t[i:]`, ending with an `assert` of its [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post).

**Solution of Exercise 16.7.**

    `def index_of_min(t, i):`

        `m = i`

        `for j in range(i + 1, len(t)):`

            `if t[j] < t[m]:`

                `m = j`

        `assert i <= m < len(t) and t[m] == min(t[i:])`

        `return m`

The invariant of the loop is “`t[m]` is a smallest element of `t[i:j]`”.

**Exercise 16.8 ★★.**

In the chapter’s `search`, a student writes `hi = mid - 1`. The loop always stops, but on the list of the output it misses $8$, $21$ and $41$. Which part of the proof fails, and why?

**Solution of Exercise 16.8.**

The keep step of the invariant. When `t[mid] > x`, every element of `t[mid:]` is larger than `x`, but `t[mid - 1]` may be `x`; `hi = mid - 1` puts it outside the window, so “`x` is not in `t[hi:]`” becomes false. The [variant](#def-g11-proving-algorithms-correct-variant) still falls, which is why the loop stops, with a wrong answer.

**Exercise 16.9 ★★.**

Prove, with an invariant, that the loop of exercise [16.4](#exo-g11-proving-algorithms-correct-4) computes the sum of `t`.

**Solution of Exercise 16.9.**

Invariant: at the start of the turn for `i`, `s` is the sum of `t[:i]`. Start: exercise [16.4](#exo-g11-proving-algorithms-correct-4). Keep: the turn adds `t[i]`, so `s` becomes the sum of `t[:i + 1]`, which is the invariant for the next `i`. End: after the last turn, `i` has gone through `len(t) - 1`, so `s` is the sum of `t[:len(t)]`, the whole list. A `for` loop over a range stops.

**Exercise 16.10 ★★.**

Write a loop that counts the occurrences of `x` in `t`, and state the invariant that proves it.

**Solution of Exercise 16.10.**

    `c = 0`

    `for i in range(len(t)):`

        `if t[i] == x:`

            `c = c + 1`

Invariant: at the start of the turn for `i`, `c` is the number of occurrences of `x` in `t[:i]`. The turn adds $1$ exactly when `t[i]` is `x`, so it is kept; at the end `c` counts the whole list.

**Exercise 16.11 ★★.**

Write `is_sorted(t)` with one loop that compares neighbours, and prove it [correct](#def-g11-proving-algorithms-correct-correct): it returns `True` exactly when `t` is sorted.

**Solution of Exercise 16.11.**

    `def is_sorted(t):`

        `for i in range(1, len(t)):`

            `if t[i - 1] > t[i]:`

                `return False`

        `return True`

Invariant: at the start of the turn for `i`, `t[:i]` is sorted. It holds for `i = 1`, a single element. If `t[i - 1] > t[i]`, the list is not sorted and `False` is right; otherwise `t[i]` is not smaller than the last element of the sorted `t[:i]`, so `t[:i + 1]` is sorted. If the loop ends without returning, `t[:len(t)]` is sorted and `True` is right. An empty list or a list of one element skips the loop and is sorted.

**Exercise 16.12 ★★★.**

Write out in full the proof that insertion sort sorts its list: the outer invariant, the inner invariant, why the inner loop keeps it, and why both loops stop.

**Solution of Exercise 16.12.**

Outer invariant: at the start of turn `i`, `t[:i]` holds the first `i` elements of the original list, sorted, and `t[i:]` is unchanged. Start: `t[:1]` has one element. Inner invariant, with $x$ the old `t[i]`: `t[:j]` is unchanged and sorted, `t[j + 1:i + 1]` holds the old `t[j:i]`, every element of which is larger than $x$. It holds when `j = i`, both slices being as they were. An inner turn copies `t[j - 1]`, larger than $x$, into place `j` and lowers `j`: kept. The inner loop stops, `j` being a [variant](#def-g11-proving-algorithms-correct-variant) that is at least $0$. When it stops, either `j = 0`, or `t[j - 1] <= x`; writing $x$ in place `j` puts it after elements not larger than it and before elements larger than it: `t[:i + 1]` is sorted and holds the old `t[:i]` and $x$. The outer invariant is kept; at the end, `i` reaches `len(t)` and the whole list is sorted. The outer loop is a `for` loop and stops.

**Exercise 16.13 ★★★.**

Prove that the chapter’s `search` returns an index of `x` whenever `x` is in the list.

**Solution of Exercise 16.13.**

Let $p$ be an index with `t[p] == x`. By the invariant, `x` is not in `t[:lo]` nor in `t[hi:]`, so $p$ always lies in the window: `lo <= p < hi`, and the window is never empty. The loop condition `lo < hi` therefore stays true, and the only way out is the `return mid`, which happens only when `t[mid] == x`. Since the [variant](#def-g11-proving-algorithms-correct-variant) `hi - lo` forces the loop to stop, the function does return, and what it returns is an index of `x`.

**Exercise 16.14 ★★★.**

The loop `while n != 1`, with `n = n // 2` if `n` is even and `n = 3 * n + 1` otherwise, stops for every `n` anyone has tried; from $27$ it takes $111$ turns. Why do neither `n` nor the number of turns left serve as a [variant](#def-g11-proving-algorithms-correct-variant)? What would a proof that it always stops need?

**Solution of Exercise 16.14.**

`n` does not always fall: an odd `n` becomes `3 * n + 1`, much larger. “The number of turns left” falls by one each turn, but it is a whole number only if the loop stops, which is what was to be proved: using it assumes the result. A proof would need some quantity, computed from `n`, that never becomes negative and falls at each turn, or a different argument altogether. Nobody has found one: whether this loop stops for every `n` is an open question, though every number tried so far reaches $1$.

**Exercise 16.15 ★★★.**

A function `f` gives `False` on `lo`, `lo + 1`, … up to some point, then `True` up to `hi - 1`. Write `first_true(f, lo, hi)` that returns the first number where `f` is true, or `hi` if there is none, by halving, with its invariant and its [variant](#def-g11-proving-algorithms-correct-variant).

**Solution of Exercise 16.15.**

    `def first_true(f, lo, hi):`

        `while lo < hi:`

            `mid = (lo + hi) // 2`

            `if f(mid):`

                `hi = mid`

            `else:`

                `lo = mid + 1`

        `return lo`

Invariant: `f` is false on every number from the first `lo` to the present `lo` excluded, and true from the present `hi` to the first `hi` excluded. A true `f(mid)` makes `f` true from `mid` on, by the [precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post); a false one makes it false up to `mid`. At the end `lo == hi`: everything before is false, everything from there is true, so `lo` is the first true, or the first `hi` if none is. [Variant](#def-g11-proving-algorithms-correct-variant): `hi - lo`, which both branches lower since `lo <= mid < hi`.

## 16.7 Problem: The Integer Square Root

**Problem 16.1.**

Weekend problem — an integer square root, proved and timed

The integer square root of a whole number $n$ is the largest whole number $r$ such that $r^2 \le n$: for $n = 15$ it is $3$, for $n = 16$ it is $4$. The program below computes it twice, by counting up from $0$ and by halving a window, and counts the turns of each.

```python
"""The weekend problem: the integer square root, by counting up and by halving."""
import math


def isqrt_linear(n):
    r, turns = 0, 0
    while (r + 1) * (r + 1) <= n:      # variant: n - r * r
        r, turns = r + 1, turns + 1
    return r, turns


def isqrt_halving(n):
    lo, hi, turns = 0, n + 1, 0
    while hi - lo > 1:                 # invariant: lo * lo <= n < hi * hi
        mid = (lo + hi) // 2
        if mid * mid <= n:
            lo = mid
        else:
            hi = mid
        turns = turns + 1
    return lo, turns


for n in [0, 1, 15, 16, 17, 1000]:
    print(f"n = {n:4}: linear {isqrt_linear(n)}, halving {isqrt_halving(n)}")
N = 10**6
worst, first = 0, None
for n in range(N + 1):
    r, turns = isqrt_halving(n)
    assert r == math.isqrt(n)
    if turns > worst:
        worst, first = turns, n
print(f"0 <= n <= {N}: halving always right,"
      f" at most {worst} turns (first at n = {first})")
print(f"linear at n = {N}: {isqrt_linear(N)[1]} turns")
```

***Listing 16.7.** Two integer square roots, checked against Python’s own on a million numbers. code/grade-11/05-proving-algorithms-correct/listings/isqrt.py*

```
$ python isqrt.py
n =    0: linear (0, 0), halving (0, 0)
n =    1: linear (1, 1), halving (1, 1)
n =   15: linear (3, 3), halving (3, 4)
n =   16: linear (4, 4), halving (4, 4)
n =   17: linear (4, 4), halving (4, 4)
n = 1000: linear (31, 31), halving (31, 9)
0 <= n <= 1000000: halving always right, at most 20 turns (first at n = 555007)
linear at n = 1000000: 1000 turns
```

***Output 16.7.** Each pair is the result and the number of turns.*

**Part I — The specification.**

1. Write the [precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) and the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) of an integer square root function.
2. Show that $r$ meets the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) exactly when $r^2 \le n < (r + 1)^2$ .
3. Give the integer square roots of $0$ , $1$ , $99$ , $100$ and $101$ .
4. Why does such an $r$ exist, and why only one?

**Part II — Counting up.**

5. State an invariant of the loop of `isqrt_linear` that, at the end, gives the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) .
6. Prove that it holds at the start and is kept.
7. Show that `n - r * r` is a [variant](#def-g11-proving-algorithms-correct-variant) .
8. How many turns does it take for $n$ ? For $n = 10^6$ ?

**Part III — Halving.**

9. Check that `lo * lo <= n < hi * hi` holds before the first turn.
10. Show that each turn keeps it, in each of the two branches.
11. Show that at the end `lo` meets the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post) .
12. Show that `mid` always lies strictly between `lo` and `hi` inside the loop.
13. Deduce a [variant](#def-g11-proving-algorithms-correct-variant) , and that the loop stops.

**Part IV — How many turns.**

14. Follow the turns of `isqrt_halving(15)` and check the count printed.
15. Show that if `hi - lo` is at most $2^k$ at the start of a turn, it is at most $2^{k - 1}$ at the end.
16. Deduce that for $n + 1 \le 2^k$ , the loop makes at most $k$ turns.
17. Compute $2^{20}$ ; deduce a bound on the turns for $n \le 10^6$ .
18. Compare with the run: maximum and first $n$ reaching it. Why is the first such $n$ not $2^{19}$ ?
19. What does the line `assert r == math.isqrt(n)` add to the proof, and what does the proof add to it?
20. State the result: correctness, [termination](#def-g11-proving-algorithms-correct-variant) and the number of turns, against counting up.

**Solution of Problem 16.1.**

**1.** [Precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post): $n$ is a whole number, $n \ge 0$. [Postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post): $r$ is a whole number, $r^2 \le n$, and no larger whole number has its square at most $n$.

**2.** For $r \ge 0$, the squares grow with $r$. So if $(r + 1)^2 > n$, every number above $r$ has a square above $n$, and $r$ is the largest; conversely the largest $r$ has $(r + 1)^2 > n$.

**3.** $0$, $1$, $9$, $10$, $10$.

**4.** $r = 0$ has $r^2 \le n$, so there is at least one candidate; a candidate $r \ge 1$ has $r \le r^2 \le n$, so there are finitely many. Their largest exists and is unique.

**5.** $r^2 \le n$. When the loop stops, its condition is false: $(r + 1)^2 > n$, and with question 2 that is the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post).

**6.** Start: $r = 0$ and $0 \le n$. Keep: a turn runs only if $(r + 1)^2 \le n$, and then sets $r$ to $r + 1$, whose square is at most $n$.

**7.** By the invariant, `n - r * r` is at least $0$; each turn raises $r$ by one, so $r^2$ grows by $2r + 1 \ge 1$ and `n - r * r` falls by at least $1$.

**8.** One turn per value of $r$ above $0$: as many turns as the result, $1000$ for $n = 10^6$, as printed.

**9.** `lo = 0` and $0 \le n$; `hi = n + 1` and $(n + 1)^2 \ge n + 1 > n$.

**10.** If `mid * mid <= n`, then `lo = mid` has its square at most $n$, and `hi` does not change. Otherwise $n < \mathit{mid}^2$, and `hi = mid` keeps $n < \mathit{hi}^2$.

**11.** At the end `hi - lo <= 1`. By the invariant $\mathit{lo}^2 \le n < \mathit{hi}^2$, so `lo < hi`, hence `hi = lo + 1` and $\mathit{lo}^2 \le n < (\mathit{lo} + 1)^2$: the [postcondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post), by question 2.

**12.** Inside the loop `hi - lo >= 2`, so $\mathit{lo} + 1 \le (\mathit{lo} + \mathit{hi}) / 2 \le
\mathit{hi} - 1$, and rounding down keeps `mid` between `lo + 1` and `hi - 1`.

**13.** `hi - lo` is a whole number, at least $2$ inside the loop; each turn replaces `lo` or `hi` by `mid`, strictly between them, so it strictly falls. The loop stops.

**14.** `lo=0, hi=16`: `mid=8`, $64 > 15$, `hi=8`; `mid=4`, $16 > 15$, `hi=4`; `mid=2`, $4 \le 15$, `lo=2`; `mid=3`, $9 \le 15$, `lo=3`; now `hi - lo = 1`. Four turns, result $3$, as printed.

**15.** The new window is `mid - lo` or `hi - mid`; these two add up to `hi - lo` and differ by at most $1$, so the larger is at most half of `hi - lo` rounded up. Half of $2^k$ is $2^{k - 1}$, already whole.

**16.** The window starts at $n + 1 \le 2^k$. After one turn it is at most $2^{k - 1}$, after two at most $2^{k - 2}$, and after $k$ turns at most $2^0 = 1$, where the loop stops: at most $k$ turns.

**17.** $2^{20} = 1\,048\,576 \ge 10^6 + 1$: at most $20$ turns for $n \le 10^6$.

**18.** The run finds $20$ turns at most, first at $n = 555\,007$. For $n + 1 \le 2^{19}$ the bound gives $19$; just above, $20$ turns are possible but not forced: whether the window shrinks to the half rounded down or rounded up depends on the branch taken, and only from $555\,007$ do enough halvings round up.

**19.** The assertion compares a million results with Python’s own function, an independent computation: it would catch a slip between the code and the proof, such as a wrong sign. The proof covers every $n$, beyond $10^6$ too, and [termination](#def-g11-proving-algorithms-correct-variant), which no test run can show.

**20.** The integer square root by halving is **[correct](#def-g11-proving-algorithms-correct-correct) for every whole $n$ and always stops**; for $n \le 10^6$ it takes **at most $20$ turns**, reached first at $n = 555\,007$, where counting up takes up to $1000$.
