IntermediateMath for DSABit Manipulation & Math

Primes: check up to √n, or sieve them all

If n has a divisor, one of them is ≤ √n, so checking stops there. For all below n, cross out multiples: the .

The idea

Divisors come in pairs: if a × b = n, one of a and b is at most √n. So to test one number, try divisors 2..√n: O(√n) instead of .

To find every prime below n, start with all numbers marked prime and, for each prime p, cross out p², p² + p, p² + 2p, … (smaller multiples were already crossed out by smaller primes).

Worked example

Primes below 20

  1. p = 2: cross out 4, 6, 8, …, 18
  2. p = 3: start at 9 and cross out 9, 12, 15, 18 (12 and 18 were already gone)
  3. p = 5: 25 ≥ 20, stop. Left: 2, 3, 5, 7, 11, 13, 17, 19.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

is_prime(n):
if n < 2: return false
for i from 2 while i × i ≤ n:
if n % i = 0: return false
return true
sieve (all primes below n):
prime ← true for every number, except 0 and 1
for p from 2 while p × p < n:
if prime[p]:
cross out p × p, p × p + p, … below n
return the numbers still marked prime

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

primes below 20

numbers (crossed out dimmed)

00
11
22
33
44
55
66
77
88
99
1010
1111
1212
1313
1414
1515
1616
1717
1818
1919

Solution · Pythonline 15

def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(n): # primes < n
if n < 3:
return 0
prime = [True] * n
prime[0] = prime[1] = False
p = 2
while p * p < n:
if prime[p]:
for multiple in range(p * p, n, p):
prime[multiple] = False
p += 1
return sum(prime)

Step 1 of 5· line 15

Assume every number is prime, except 0 and 1. Then, for each prime p, cross out its multiples: they can't be prime.

  • inside the window
  • finished

is_prime: O(√n). Sieve: O(n log log n) time, O(n) space.

How to spot it

  • “count primes”, “prime factors”, “is n prime”, many prime checks at once (use the sieve).

Common mistakes

  • Looping to n instead of √n.
  • Treating 1 as prime.

Practise the ideas first

Where it comes up

Go further