计算机科学 · 第 1 册 · 1–9 年级

Primary & Middle School Computer Science

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

Primary & Middle School Computer Science · 1–9 年级

34Algorithms on Numbers

Is 1,000,003 a prime number? To find out by hand, you would try to divide it by 2, by 3, by 4, and so on: about a million divisions, weeks of work. A short program does them in a moment. A better program does a thousand times fewer, because it knows where to stop. This chapter programs some of the oldest algorithms there are, and counts the work they do.

You already know

A function takes parameters and returns a value (Chapter 19); a while loop repeats as long as a condition holds (Chapter 18); a binary search halves the part of a sorted list that is left at each step (Chapter 28). From mathematics: a divisor of nn divides it with no remainder; a prime number has exactly two divisors, 1 and itself; the greatest common divisor (gcd) of two numbers is found by Euclid’s algorithm.

34.1 Divisors and primality by trial division

The operator % gives the remainder of a division: n % d == 0 means that d divides n. Listing the divisors is one loop:

def divisors(n):
    """The divisors of n, from 1 to n."""
    found = []
    for d in range(1, n + 1):
        if n % d == 0:
            found.append(d)
    return found


print(divisors(36))
print(divisors(37))
Listing 34.1. The divisors of a number. code/grade-9/04-algorithms-on-numbers/listings/divisors.py
$ python divisors.py
[1, 2, 3, 4, 6, 9, 12, 18, 36]
[1, 37]
Output 34.1. 36 has nine divisors, 37 only two.

Definition 34.1 (Primality test)

A primality test is an algorithm that tells, for a whole number, whether it is prime.

Method 34.2 (Trial division)

To test whether n≥2n \ge 2 is prime, try to divide it by 2, 3, 4, and so on. If one of them divides nn, it is not prime; if none does, it is.

The program below counts the divisions it tries:

def is_prime_slow(n):
    """True when n is prime; also the number of divisions tried."""
    divisions = 0
    for d in range(2, n):
        divisions = divisions + 1
        if n % d == 0:
            return False, divisions
    return n >= 2, divisions


for n in [91, 97, 1_000_003]:
    print(n, is_prime_slow(n))
Listing 34.2. Trial division by every number below n. code/grade-9/04-algorithms-on-numbers/listings/is_prime_slow.py
$ python is_prime_slow.py
91 (False, 6)
97 (True, 95)
1000003 (True, 1000001)
Output 34.2. A prime costs a division for every number below it.

91=7×1391 = 7 \times 13 is found out after 6 divisions. A prime is the worst case: nothing divides it, so every number from 2 to n−1n - 1 is tried, more than a million divisions for 1,000,003.

34.2 Stopping at the square root

Divisors come in pairs: if dd divides nn, so does n/dn / d. For 36, the pairs are 1×361 \times 36, 2×182 \times 18, 3×123 \times 12, 4×94 \times 9 and 6×66 \times 6.

The divisor pairs of 36 as rectangles of area 36. In each pair, one side is at most 6 and the other at least 6. The square 6 × 6 is where the pairs turn round: after it, 9 × 4, 12 × 3, … only repeat them.
The divisor pairs of 36 as rectangles of area 36. In each pair, one side is at most 6 and the other at least 6. The square 6×66 \times 6 is where the pairs turn round: after it, 9×49 \times 4, 12×312 \times 3, … only repeat them.

Proposition 34.3 (A divisor below the square root)

If a whole number n≥2n \ge 2 is not prime, it has a divisor dd with 2≤d2 \le d and d×d≤nd \times d \le n.

Proof. As nn is not prime, n=d×en = d \times e with dd and ee both between 2 and n−1n - 1. Say d≤ed \le e. If d×dd \times d were larger than nn, then d×e≥d×d>nd \times e \ge d \times d > n, which is false. So d×d≤nd \times d \le n. ∎

So the test can stop as soon as d×d>nd \times d > n: if no divisor was found by then, there is none.

def is_prime(n):
    """True when n is prime; also the number of divisions tried."""
    if n < 2:
        return False, 0
    divisions = 0
    d = 2
    while d * d <= n:                  # stop at the square root of n
        divisions = divisions + 1
        if n % d == 0:
            return False, divisions
        d = d + 1
    return True, divisions


if __name__ == "__main__":
    for n in [91, 97, 1_000_003]:
        print(n, is_prime(n))
Listing 34.3. Trial division up to the square root. code/grade-9/04-algorithms-on-numbers/listings/is_prime.py
$ python is_prime.py
91 (False, 6)
97 (True, 8)
1000003 (True, 999)
Output 34.3. 999 divisions instead of 1,000,001.

The square root of 1,000,003 is just above 1,000, so the loop tries d=2d = 2 to 1,0001{,}000: 999 divisions. For a number nn, the work falls from about nn divisions to about n\sqrt{n}. The test is written d * d <= n rather than with a square root, so that it uses whole numbers only.

34.3 The sieve for all the primes below a number

To find all the primes below 100, testing each number one by one repeats work. A list can remember what is already known.

Method 34.4 (Sieve of Eratosthenes)

To find the primes below nn, write the numbers from 2 to n−1n - 1. Take the smallest number not crossed out: it is prime. Cross out its multiples. Repeat with the next number not crossed out, until the end of the list.

In Python, a list of nn Booleans says, for each number, whether it is still in:

def sieve(n):
    """The prime numbers below n, by crossing out multiples."""
    prime = [True] * n
    prime[0] = False
    prime[1] = False
    for p in range(2, n):
        if prime[p]:
            for multiple in range(p * p, n, p):
                prime[multiple] = False
    primes = []
    for k in range(n):
        if prime[k]:
            primes.append(k)
    return primes


if __name__ == "__main__":
    print(sieve(50))
    print(len(sieve(100_000)), "primes below 100,000")
Listing 34.4. The sieve. code/grade-9/04-algorithms-on-numbers/listings/sieve.py
$ python sieve.py
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
9592 primes below 100,000
Output 34.4. The primes below 50, and how many there are below 100,000.

Crossing out starts at p×pp \times p, not at 2×p2 \times p: Exercise 34.9 asks why that is enough. Printed as a grid of ten rows, the sieve shows where the primes fall:

from sieve import sieve

primes = sieve(101)
for row in range(10):
    line = ""
    for col in range(1, 11):
        k = row * 10 + col
        if k in primes:
            line = line + f"{k:>4}"
        else:
            line = line + "   ."
    print(line)
Listing 34.5. The primes up to 100, as a grid. code/grade-9/04-algorithms-on-numbers/listings/sieve_grid.py
$ python sieve_grid.py
   .   2   3   .   5   .   7   .   .   .
  11   .  13   .   .   .  17   .  19   .
   .   .  23   .   .   .   .   .  29   .
  31   .   .   .   .   .  37   .   .   .
  41   .  43   .   .   .  47   .   .   .
   .   .  53   .   .   .   .   .  59   .
  61   .   .   .   .   .  67   .   .   .
  71   .  73   .   .   .   .   .  79   .
   .   .  83   .   .   .   .   .  89   .
   .   .   .   .   .   .  97   .   .   .
Output 34.5. A dot for each number crossed out.
The 25 primes up to 100, from the output of the sieve. After 2 and 5, every prime ends in 1, 3, 7 or 9: the other columns hold multiples of 2 or of 5.
The 25 primes up to 100, from the output of the sieve. After 2 and 5, every prime ends in 1, 3, 7 or 9: the other columns hold multiples of 2 or of 5.

History — A librarian’s sieve

Eratosthenes was born in Cyrene, in today’s Libya, about 276 BC, and died in Alexandria about 194 BC. He was the third librarian of the great library of Alexandria. He is remembered for the prime number sieve that carries his name, still used today in a modified form.

How much faster is the sieve? This program finds the primes below 100,000 both ways and times them:

import time

from is_prime import is_prime
from sieve import sieve

start = time.perf_counter()
count = 0
for n in range(100_000):
    if is_prime(n)[0]:
        count = count + 1
middle = time.perf_counter()
by_sieve = len(sieve(100_000))
end = time.perf_counter()
print(f"trial division: {count} primes in {middle - start:.3f} s")
print(f"sieve:          {by_sieve} primes in {end - middle:.3f} s")
Listing 34.6. Trial division against the sieve. code/grade-9/04-algorithms-on-numbers/listings/primes_timing.py
$ python primes_timing.py
trial division: 9592 primes in 0.083 s
sieve:          9592 primes in 0.005 s
Output 34.6. Timings on the author’s laptop; yours will differ.

Both find the same 9,592 primes; the sieve is many times faster, because each number is crossed out by a few additions instead of being divided again and again.

Facts as of 2026

The largest prime number known in 2026 is 2136 279 841−12^{136\,279\,841} - 1, found in October 2024 by a project in which volunteers lend their computers to the search. Written out, it has 41,024,320 digits. No sieve could reach it: it was proved prime by a test made for numbers of the form 2p−12^p - 1.

34.4 Euclid’s algorithm programmed

The gcd of two numbers also divides their difference. Euclid’s algorithm in its oldest form subtracts the smaller number from the larger until both are equal:

def gcd_subtract(a, b):
    """Euclid's algorithm by subtraction: take the smaller from the larger."""
    while a != b:
        print(a, b)
        if a > b:
            a = a - b
        else:
            b = b - a
    return a


print("gcd:", gcd_subtract(84, 30))
Listing 34.7. Euclid by subtraction. code/grade-9/04-algorithms-on-numbers/listings/gcd_subtract.py
$ python gcd_subtract.py
84 30
54 30
24 30
24 6
18 6
12 6
gcd: 6
Output 34.7. The gcd of 84 and 30.

Subtracting 30 from 84 twice is what a division does at once: 84=2×30+2484 = 2 \times 30 + 24. Euclid’s algorithm by division replaces the pair (a,b)(a, b) by (b,a mod b)(b, a \bmod b), the remainder, until bb is 0:

def gcd(a, b):
    """Euclid's algorithm by division; also the number of division steps."""
    steps = 0
    while b != 0:
        a, b = b, a % b
        steps = steps + 1
    return a, steps


if __name__ == "__main__":
    for a, b in [[84, 30], [1071, 462], [1_000_000, 999_999]]:
        print(a, b, "->", gcd(a, b))
Listing 34.8. Euclid by division, counting the steps. code/grade-9/04-algorithms-on-numbers/listings/gcd.py
$ python gcd.py
84 30 -> (6, 3)
1071 462 -> (21, 3)
1000000 999999 -> (1, 2)
Output 34.8. A gcd and the number of steps.

The line a, b = b, a % b changes both variables at once: the new b is computed from the old a and b. Subtraction would need 999,999 steps for the last pair; division needs 2.

Euclid on 21 and 13: cut the largest square from the rectangle, then from what is left, again and again. The last squares, 1 by 1, fit exactly: the gcd is 1. Each step cuts as many squares as its quotient: one, five times, then two squares of side 1; six steps in all.
Euclid on 21 and 13: cut the largest square from the rectangle, then from what is left, again and again. The last squares, 1 by 1, fit exactly: the gcd is 1. Each step cuts as many squares as its quotient: one, five times, then two squares of side 1; six steps in all.

34.5 Why Euclid is fast

Proposition 34.5 (The remainders halve)

If 0<b≤a0 < b \le a, then the remainder a mod ba \bmod b is less than a/2a / 2.

Proof. Two cases. If b≤a/2b \le a / 2, the remainder is smaller than bb, so smaller than a/2a / 2. If b>a/2b > a / 2, then bb fits once into aa and the remainder is a−ba - b, which is less than a−a/2=a/2a - a / 2 = a / 2. ∎

After two steps, the pair (a,b)(a, b) has become (b,r)(b, r), then (r,…)(r, \ldots): the larger number is now rr, less than half of aa. Every two steps halve the larger number at least, so for numbers below 1,000, which can be halved only ten times before reaching 1, Euclid needs at most about twenty steps. The chart below shows the real counts: they grow very slowly.

For each a up to 200, the largest number of division steps of Euclid’s algorithm over all pairs (a, b) with b < a, computed by the chapter’s gcd. A new record (red) is set only at a few values of a.
For each aa up to 200, the largest number of division steps of Euclid’s algorithm over all pairs (a,b)(a, b) with b<ab < a, computed by the chapter’s gcd. A new record (red) is set only at a few values of aa.

34.6 A square root by halving

The halving of binary search also finds numbers. 1×1<2<2×21 \times 1 < 2 < 2 \times 2, so 2\sqrt{2} lies between 1 and 2.

Method 34.6 (Square root by halving)

To approach 2\sqrt{2}, start with an interval whose ends’ squares are below and above 2. Take its middle. If the middle’s square is below 2, the middle becomes the lower end; otherwise it becomes the upper end. Repeat: each step halves the interval.

low = 1.0
high = 2.0                     # 1 * 1 < 2 < 2 * 2
for step in range(1, 11):
    middle = (low + high) / 2
    if middle * middle < 2:
        low = middle
    else:
        high = middle
    print(f"{step:>2}: {low:.6f} < root of 2 < {high:.6f}")
Listing 34.9. Ten halvings for the square root of 2. code/grade-9/04-algorithms-on-numbers/listings/sqrt_halving.py
$ python sqrt_halving.py
 1: 1.000000 < root of 2 < 1.500000
 2: 1.250000 < root of 2 < 1.500000
 3: 1.375000 < root of 2 < 1.500000
 4: 1.375000 < root of 2 < 1.437500
 5: 1.406250 < root of 2 < 1.437500
 6: 1.406250 < root of 2 < 1.421875
 7: 1.414062 < root of 2 < 1.421875
 8: 1.414062 < root of 2 < 1.417969
 9: 1.414062 < root of 2 < 1.416016
10: 1.414062 < root of 2 < 1.415039
Output 34.9. The interval shrinks around 1.414.

After ten halvings the interval is 1/10241 / 1024 wide, less than a thousandth: the square root of 2 is 1.414 to three decimals. Each halving gains one binary digit, so about one decimal digit every three or four steps.

34.7 Exercises

Exercise 34.1 ★

What does divisors(28) return? Add up the divisors smaller than 28. What do you notice?

Solution

Solution of Exercise 34.1.

[1, 2, 4, 7, 14, 28]. The divisors smaller than 28 add up to 1+2+4+7+14=281 + 2 + 4 + 7 + 14 = 28: the number itself. 28 is a perfect number (Exercise 34.4).

Exercise 34.2 ★

On the numbers from 2 to 30, cross out the multiples of 2, then of 3, as the sieve does. Which numbers are left? Which of them are not prime?

Solution

Solution of Exercise 34.2.

Left: 2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29. All are prime except 25, a multiple of 5: the sieve crosses it out at the next turn, when 5 is taken.

Exercise 34.3 ★

Write the pairs that gcd(48, 18) goes through, step by step. How many steps does it take, and what does it return?

Solution

Solution of Exercise 34.3.

(48,18)→(18,12)→(12,6)→(6,0)(48, 18) \to (18, 12) \to (12, 6) \to (6, 0): three steps, and the result is 6.

Exercise 34.4 ★

A number is perfect when it equals the sum of its divisors smaller than itself, like 6 =1+2+3= 1 + 2 + 3. Write a program that prints the perfect numbers below 1,000.

Solution

Solution of Exercise 34.4.

def divisor_sum(n):
    """The sum of the divisors of n that are smaller than n."""
    total = 0
    for d in range(1, n // 2 + 1):
        if n % d == 0:
            total = total + d
    return total


for n in range(2, 1000):
    if divisor_sum(n) == n:
        print(n)
Perfect numbers below 1,000. code/grade-9/04-algorithms-on-numbers/exercises/perfect.py

It prints 6, 28 and 496. A divisor smaller than nn is at most n/2n / 2, so the loop stops there.

Exercise 34.5 ★★

This test says that 1 is prime. Why? Fix it.

def is_prime(n):
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d = d + 1
    return True
Listing 34.10. A primality test with a gap. code/grade-9/04-algorithms-on-numbers/exercises/is_prime_one_bug.py
Solution

Solution of Exercise 34.5.

For n=1n = 1, the condition 2 * 2 <= 1 is false at once: the loop never runs, and the function reaches return True. The fix rules out the numbers below 2 first:

def is_prime(n):
    if n < 2:                  # 0 and 1 are not prime
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d = d + 1
    return True
Numbers below 2 are not prime. code/grade-9/04-algorithms-on-numbers/exercises/is_prime_one_fixed.py

Exercise 34.6 ★★

In this version the loop runs while d * d < n. Which numbers does it wrongly call prime? Find the smallest one, then fix the test.

def is_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d < n:
        if n % d == 0:
            return False
        d = d + 1
    return True
Listing 34.11. One character changed. code/grade-9/04-algorithms-on-numbers/exercises/square_bug.py
Solution

Solution of Exercise 34.6.

The squares of primes: 4, 9, 25, 49, and so on. For 4, the loop needs 2 * 2 < 4, which is false, so 2 is never tried; the smallest wrong answer is 4. A square of a prime has no divisor below its square root, only the root itself, so the loop must include d×d=nd \times d = n: write d * d <= n.

Exercise 34.7 ★★

Write a function gcd3(a, b, c) for the gcd of three numbers, using the gcd of two. Try it on 84, 126 and 210.

Solution

Solution of Exercise 34.7.

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def gcd3(a, b, c):
    """The greatest common divisor of three numbers."""
    return gcd(gcd(a, b), c)


print(gcd3(84, 126, 210))
The gcd of three numbers. code/grade-9/04-algorithms-on-numbers/exercises/gcd3.py

It prints 42. A number divides aa, bb and cc exactly when it divides gcd⁡(a,b)\gcd(a, b) and cc.

Exercise 34.8 ★★

Twin primes are two primes that differ by 2, like 11 and 13. Write a program that counts the pairs of twin primes below 1,000 and prints the last pair.

Solution

Solution of Exercise 34.8.

def is_prime(n):
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d = d + 1
    return True


pairs = []
for p in range(2, 1000 - 2):
    if is_prime(p) and is_prime(p + 2):
        pairs.append([p, p + 2])
print(len(pairs), "pairs; the last:", pairs[-1])
Twin primes below 1,000. code/grade-9/04-algorithms-on-numbers/exercises/twins.py

It prints 35 pairs; the last: [881, 883].

Exercise 34.9 ★★

The sieve starts crossing out the multiples of pp at p×pp \times p. Why have the smaller multiples, such as 2×p2 \times p and 3×p3 \times p, already been crossed out?

Solution

Solution of Exercise 34.9.

A multiple k×pk \times p with k<pk < p has a factor kk smaller than pp, so a prime smaller than pp divides it. That prime was taken earlier, and its multiples, k×pk \times p among them, are already crossed out.

Exercise 34.10 ★★★

10,007 is prime. Without running the program, how many divisions does is_prime(10007) try?

Solution

Solution of Exercise 34.10.

100×100=10,000≤10,007100 \times 100 = 10{,}000 \le 10{,}007 but 101×101=10,201101 \times 101 = 10{,}201: the loop tries d=2d = 2 to 100, that is 99 divisions, and finds no divisor. A test of the chapter checks it.

Exercise 34.11 ★★★

Use the proposition on halving remainders to find an upper bound on the number of division steps of Euclid’s algorithm for two numbers below 1,000. Compare it with the real record, found by the weekend problem.

Solution

Solution of Exercise 34.11.

Every two steps, the larger number falls below half of what it was. A number below 1,000 is below 210=1,0242^{10} = 1{,}024, so after 20 steps the larger number would be below 1, which cannot be: the algorithm has stopped by then. At most about 20 steps; the real record is 14, for (987,610)(987, 610).

Exercise 34.12 ★★★

Write a function next_prime(n) that returns the smallest prime larger than n, together with the total number of divisions it tried on the way. Add a few lines that ask the user for n.

Solution

Solution of Exercise 34.12.

Saved next to is_prime.py, the function tries each candidate in turn with the fast test, adding up the divisions, while the candidate is not prime:

from is_prime import is_prime


def next_prime(n):
    """The smallest prime above n, and the divisions tried to find it."""
    candidate = n + 1
    prime, divisions = is_prime(candidate)
    while not prime:
        candidate = candidate + 1
        prime, tried = is_prime(candidate)
        divisions = divisions + tried
    return candidate, divisions


if __name__ == "__main__":
    n = int(input("A whole number: "))
    print(next_prime(n))
The next prime and its cost. code/grade-9/04-algorithms-on-numbers/exercises/next_prime.py

For 1,000 it returns (1009, 76): 1,001 to 1,008 are thrown out after a few divisions each, and 1,009 needs 30. A test checks these values.

34.8 Problem: The Slowest Pairs for Euclid

Problem 34.1

Weekend problem — the slowest pairs for Euclid

Euclid’s algorithm is fast, but some pairs make it work harder than others. Which pair of numbers below 1,000 takes the most steps?

Part I — By hand.

  1. Count the division steps of Euclid’s algorithm for (13,8)(13, 8).
  2. The same for (21,13)(21, 13); compare with the figure of the squares.
  3. The same for (100,1)(100, 1). Are large numbers always slow?

Part II — A search for records.

from gcd import gcd

record = 0
for a in range(1, 1000):
    for b in range(1, a):
        steps = gcd(a, b)[1]
        if steps > record:
            record = steps
            print(f"{a:>4} {b:>4}: {steps:>2} steps")
Listing 34.12. Every pair below 1,000, printing each new record. code/grade-9/04-algorithms-on-numbers/listings/slowest_pairs.py
  1. How many pairs does the program try?
  2. Why does it print only some pairs, and not every pair?
  3. Run it. Which pair holds the final record, and with how many steps?
  4. Look at the numbers in the record pairs. How is each number made from the two before it?
  5. What is the next record pair, above 1,000?

Part III — Why these pairs.

  1. For a record pair (a,b)(a, b), what is the quotient at each step?
  2. Show that one step of Euclid on a record pair gives the record pair just before it.
  3. Why do quotients of 1 make the algorithm as slow as it can be?
  4. State the result.
Solution

Solution of Problem 34.1.

1. (13,8)→(8,5)→(5,3)→(3,2)→(2,1)→(1,0)(13, 8) \to (8, 5) \to (5, 3) \to (3, 2) \to (2, 1) \to (1, 0): 5 steps.

2. One more, 6 steps: the six cuts of the figure.

3. One step: 100 mod 1=0100 \bmod 1 = 0. Size alone does not make a pair slow.

4. Every pair with 1≤b<a≤9991 \le b < a \le 999: 999×998/2=498,501999 \times 998 / 2 = 498{,}501 pairs.

5. It prints a pair only when it beats the best count so far.

$ python slowest_pairs.py
   2    1:  1 steps
   3    2:  2 steps
   5    3:  3 steps
   8    5:  4 steps
  13    8:  5 steps
  21   13:  6 steps
  34   21:  7 steps
  55   34:  8 steps
  89   55:  9 steps
 144   89: 10 steps
 233  144: 11 steps
 377  233: 12 steps
 610  377: 13 steps
 987  610: 14 steps
Output 34.10. The record pairs below 1,000.

6. (987,610)(987, 610), with 14 steps.

7. Each number is the sum of the two before it: 13=8+513 = 8 + 5, 21=13+821 = 13 + 8, …: the sequence 1, 1, 2, 3, 5, 8, 13, …8. (987+610,987)=(1597,987)(987 + 610, 987) = (1597, 987), with 15 steps.

9. 1 at every step, except the last one, (2,1)(2, 1), where it is 2.

10. If a=b+ca = b + c for the number cc just before bb in the sequence, then c<bc < b, so a mod b=ca \bmod b = c: the step turns (a,b)(a, b) into (b,c)(b, c), the record pair just before.

11. A quotient of 1 removes as little as possible from aa. Larger quotients make the numbers fall faster, so fewer steps are needed.

12. Result. Below 1,000, the pair (987,610)(987, 610) takes the most division steps, 14. The record pairs are neighbouring numbers of the sequence 1, 1, 2, 3, 5, 8, 13, …, because each step of Euclid takes such a pair back exactly one place.

本章定义的术语

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