本书暂未推出简体中文版。现有版本: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 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))
$ python divisors.py
[1, 2, 3, 4, 6, 9, 12, 18, 36]
[1, 37]
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 is prime, try to divide it by 2, 3, 4, and so on. If one of them divides , 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))
$ python is_prime_slow.py
91 (False, 6)
97 (True, 95)
1000003 (True, 1000001)
is found out after 6 divisions. A prime is the worst case: nothing divides it, so every number from 2 to is tried, more than a million divisions for 1,000,003.
34.2 Stopping at the square root
Divisors come in pairs: if divides , so does . For 36, the pairs are , , , and .
Proposition 34.3 (A divisor below the square root)
If a whole number is not prime, it has a divisor with and .
Proof. As is not prime, with and both between 2 and . Say . If were larger than , then , which is false. So . ∎
So the test can stop as soon as : 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))
$ python is_prime.py
91 (False, 6)
97 (True, 8)
1000003 (True, 999)
The square root of 1,000,003 is just above 1,000, so the loop tries to : 999 divisions. For a number , the work falls from about divisions to about . 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 , write the numbers from 2 to . 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 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")
$ python sieve.py
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
9592 primes below 100,000
Crossing out starts at , not at : 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)
$ 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 . . .
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")
$ python primes_timing.py
trial division: 9592 primes in 0.083 s
sieve: 9592 primes in 0.005 s
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 , 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 .
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))
$ python gcd_subtract.py
84 30
54 30
24 30
24 6
18 6
12 6
gcd: 6
Subtracting 30 from 84 twice is what a division does at once: . Euclid’s algorithm by division replaces the pair by , the remainder, until 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))
$ python gcd.py
84 30 -> (6, 3)
1071 462 -> (21, 3)
1000000 999999 -> (1, 2)
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.
34.5 Why Euclid is fast
Proposition 34.5 (The remainders halve)
If , then the remainder is less than .
Proof. Two cases. If , the remainder is smaller than , so smaller than . If , then fits once into and the remainder is , which is less than . ∎
After two steps, the pair has become , then : the larger number is now , less than half of . 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.
gcd. A new record (red) is set only at a few values of .34.6 A square root by halving
The halving of binary search also finds numbers. , so lies between 1 and 2.
Method 34.6 (Square root by halving)
To approach , 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}")
$ 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
After ten halvings the interval is 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 : 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.
: 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 . 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)
It prints 6, 28 and 496. A divisor smaller than is at most , 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
Solution
Solution of Exercise 34.5.
For , 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
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
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 : 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))
It prints 42. A number divides , and exactly when it divides and .
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])
It prints 35 pairs; the last: [881, 883].
Exercise 34.9 ★★
The sieve starts crossing out the multiples of at . Why have the smaller multiples, such as and , already been crossed out?
Solution
Solution of Exercise 34.9.
A multiple with has a factor smaller than , so a prime smaller than divides it. That prime was taken earlier, and its multiples, 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.
but : the loop tries 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 , 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 .
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))
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.
- Count the division steps of Euclid’s algorithm for .
- The same for ; compare with the figure of the squares.
- The same for . 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")
- How many pairs does the program try?
- Why does it print only some pairs, and not every pair?
- Run it. Which pair holds the final record, and with how many steps?
- Look at the numbers in the record pairs. How is each number made from the two before it?
- What is the next record pair, above 1,000?
Part III — Why these pairs.
- For a record pair , what is the quotient at each step?
- Show that one step of Euclid on a record pair gives the record pair just before it.
- Why do quotients of 1 make the algorithm as slow as it can be?
- State the result.
Solution
Solution of Problem 34.1.
1. : 5 steps.
2. One more, 6 steps: the six cuts of the figure.
3. One step: . Size alone does not make a pair slow.
4. Every pair with : 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
6. , with 14 steps.
7. Each number is the sum of the two before it: , , …: the sequence 1, 1, 2, 3, 5, 8, 13, …8. , with 15 steps.
9. 1 at every step, except the last one, , where it is 2.
10. If for the number just before in the sequence, then , so : the step turns into , the record pair just before.
11. A quotient of 1 removes as little as possible from . Larger quotients make the numbers fall faster, so fewer steps are needed.
12. Result. Below 1,000, the pair 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.