计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

16Proving 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). 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. 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 stops: a whole number that is at least 00 and loses at least 11 at each turn cannot do so more times than its first value. Euclid’s algorithm is an example. Its variant is bb: the new bb is the remainder a % b, which is smaller than bb and never negative.

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 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 bb falls at each turn and the loop stops when it reaches 00: 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.
The variant of gcd(233, 144), from the run above: a staircase that only goes down, one step per turn, and cannot go below 00.

The variant does not have to fall by 11 each turn; it may fall by much more. What matters is that it falls by at least 11 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, it stops and its result meets the postcondition.

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.

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.
  5. Give a 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: len(t) - i.

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:].

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.
Selection sort at the start of turn 22: the sorted part, the rest, and the swap that will put a smallest element of the rest in place 22.

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 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.

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 ii, the first i+1i + 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.
Turn 44 of insertion sort. The sorted part was 3,12,29,473, 12, 29, 47; the elements larger than x=18x = 18 move one place right, first 4747 then 2929, and xx 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 xx, in order, and putting xx in place j would give the old t[:i] with xx added. Each inner turn moves one larger element right and lowers j; the inner loop stops when j is 00 or when t[j - 1] is not larger than xx. In both cases xx, 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 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.

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

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 is hi - lo: mid lies in the window, so both lo = mid + 1 and hi = mid make it smaller.

The variant is where the opening bug hides. Writing lo = mid keeps the invariant, but not the variant: when hi = lo + 1, mid equals lo, and lo = mid changes nothing.

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

Solution of Exercise 16.1.

Turn 00 swaps the smallest, 11, into place 00: [1, 2, 9, 5, 7]. Turn 11 finds 22 already in place 11: the list stays [1, 2, 9, 5, 7].

Exercise 16.2 ★

Give a variant of the loop while n > 0: n = n - 2, for n a whole number, and say why it is one.

Solution

Solution of Exercise 16.2.

n itself, if n starts at 00 or more: it falls by 22 at each turn, and the loop runs only while n > 0, so during the loop it is a whole number at least 11. (If n starts odd, it ends at −1-1; the 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 5252 in the list of the output.

Solution

Solution of Exercise 16.3.

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

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

Solution of Exercise 16.4.

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

Exercise 16.5 ★

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

Solution

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 1111 is missed.

Exercise 16.6 ★★

Prove that this loop stops for every whole number n, by giving a variant: while n > 1, if n is even, n = n // 2, otherwise n = n - 1.

Solution

Solution of Exercise 16.6.

n is a variant. Inside the loop n > 1; then n // 2 and n - 1 are both whole numbers smaller than n and at least 11. 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.

Solution

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 88, 2121 and 4141. Which part of the proof fails, and why?

Solution

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 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 computes the sum of t.

Solution

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. 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

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 11 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: it returns True exactly when t is sorted.

Solution

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

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 xx 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 xx. It holds when j = i, both slices being as they were. An inner turn copies t[j - 1], larger than xx, into place j and lowers j: kept. The inner loop stops, j being a variant that is at least 00. When it stops, either j = 0, or t[j - 1] <= x; writing xx 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 xx. 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

Solution of Exercise 16.13.

Let pp be an index with t[p] == x. By the invariant, x is not in t[:lo] nor in t[hi:], so pp 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 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 2727 it takes 111111 turns. Why do neither n nor the number of turns left serve as a variant? What would a proof that it always stops need?

Solution

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 11.

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.

Solution

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; 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: 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 nn is the largest whole number rr such that r2≤nr^2 \le n: for n=15n = 15 it is 33, for n=16n = 16 it is 44. The program below computes it twice, by counting up from 00 and by halving a window, and counts the turns of each.

"""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 and the postcondition of an integer square root function.
  2. Show that rr meets the postcondition exactly when r2≤n<(r+1)2r^2 \le n < (r + 1)^2.
  3. Give the integer square roots of 00, 11, 9999, 100100 and 101101.
  4. Why does such an rr exist, and why only one?

Part II — Counting up.

  1. State an invariant of the loop of isqrt_linear that, at the end, gives the postcondition.
  2. Prove that it holds at the start and is kept.
  3. Show that n - r * r is a variant.
  4. How many turns does it take for nn? For n=106n = 10^6?

Part III — Halving.

  1. Check that lo * lo <= n < hi * hi holds before the first turn.
  2. Show that each turn keeps it, in each of the two branches.
  3. Show that at the end lo meets the postcondition.
  4. Show that mid always lies strictly between lo and hi inside the loop.
  5. Deduce a variant, and that the loop stops.

Part IV — How many turns.

  1. Follow the turns of isqrt_halving(15) and check the count printed.
  2. Show that if hi - lo is at most 2k2^k at the start of a turn, it is at most 2k−12^{k - 1} at the end.
  3. Deduce that for n+1≤2kn + 1 \le 2^k, the loop makes at most kk turns.
  4. Compute 2202^{20}; deduce a bound on the turns for n≤106n \le 10^6.
  5. Compare with the run: maximum and first nn reaching it. Why is the first such nn not 2192^{19}?
  6. What does the line assert r == math.isqrt(n) add to the proof, and what does the proof add to it?
  7. State the result: correctness, termination and the number of turns, against counting up.
Solution

Solution of Problem 16.1.

1. Precondition: nn is a whole number, n≥0n \ge 0. Postcondition: rr is a whole number, r2≤nr^2 \le n, and no larger whole number has its square at most nn.

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

3. 00, 11, 99, 1010, 1010.

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

5. r2≤nr^2 \le n. When the loop stops, its condition is false: (r+1)2>n(r + 1)^2 > n, and with question 2 that is the postcondition.

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

7. By the invariant, n - r * r is at least 00; each turn raises rr by one, so r2r^2 grows by 2r+1≥12r + 1 \ge 1 and n - r * r falls by at least 11.

8. One turn per value of rr above 00: as many turns as the result, 10001000 for n=106n = 10^6, as printed.

9. lo = 0 and 0≤n0 \le n; hi = n + 1 and (n+1)2≥n+1>n(n + 1)^2 \ge n + 1 > n.

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

11. At the end hi - lo <= 1. By the invariant lo2≤n<hi2\mathit{lo}^2 \le n < \mathit{hi}^2, so lo < hi, hence hi = lo + 1 and lo2≤n<(lo+1)2\mathit{lo}^2 \le n < (\mathit{lo} + 1)^2: the postcondition, by question 2.

12. Inside the loop hi - lo >= 2, so lo+1≤(lo+hi)/2≤hi−1\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 22 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>1564 > 15, hi=8; mid=4, 16>1516 > 15, hi=4; mid=2, 4≤154 \le 15, lo=2; mid=3, 9≤159 \le 15, lo=3; now hi - lo = 1. Four turns, result 33, as printed.

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

16. The window starts at n+1≤2kn + 1 \le 2^k. After one turn it is at most 2k−12^{k - 1}, after two at most 2k−22^{k - 2}, and after kk turns at most 20=12^0 = 1, where the loop stops: at most kk turns.

17. 220=1 048 576≥106+12^{20} = 1\,048\,576 \ge 10^6 + 1: at most 2020 turns for n≤106n \le 10^6.

18. The run finds 2020 turns at most, first at n=555 007n = 555\,007. For n+1≤219n + 1 \le 2^{19} the bound gives 1919; just above, 2020 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 007555\,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 nn, beyond 10610^6 too, and termination, which no test run can show.

20. The integer square root by halving is correct for every whole nn and always stops; for n≤106n \le 10^6 it takes at most 2020 turns, reached first at n=555 007n = 555\,007, where counting up takes up to 10001000.

本章定义的术语

在术语表中查看全部 1050 个术语