Count Primes

Medium

Topics
MathSieve of Eratosthenes

Given an integer n, return the number of prime numbers strictly less than n.

Example 1

0123456789
primecrossed out
Counting what survives below 10 gives 4.
Cells are the numbers themselves; the answer counts primes strictly below n.
Input:  n = 10
Output: 4

Example 2

Input:  n = 0
Output: 0

Example 3

01
crossed out
Input:  n = 2
Output: 0

Constraints

  • 0 <= n <= 5*10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Testing each number for primality by trial division costs O(sqrt n) per candidate, so O(n sqrt n) overall. At n up to 5*10^6 that is far too slow.

The sieve of Eratosthenes inverts the work. Instead of asking "is k prime", it crosses off composites: take each prime and mark every multiple of it. Nothing is ever tested; numbers that survive the marking are prime by construction.

Two optimisations matter and both are in the code:

  • Start marking at i*i, not 2*i. Any smaller multiple of i has a factor below i and was already crossed off when that smaller prime was processed.
  • Stop the outer loop at i*i >= n. A composite below n must have a factor at or below its square root, so every composite is caught by then.

The running time is O(n log log n), which is the sum of n/p over primes p — close enough to linear that the log log factor rarely matters in practice.

Approach

  1. A boolean array of size n, all true; mark 0 and 1 false.
  2. For each i while i*i < n: if i is still marked prime, cross off i*i, i*i+i, i*i+2i, ...
  3. Count the survivors.

Dry Run

n = 20, counting primes strictly below 20

start      [F,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T]
                 2 3 4 5 6 7 8 9 ...

i=2  prime, cross 4,6,8,10,12,14,16,18
i=3  prime, cross 9,15          (6 and 12 already gone)
i=4  i*i = 16 < 20 but 4 is already crossed, skip
i=5  i*i = 25 >= 20, loop ends

survivors 2,3,5,7,11,13,17,19  -> answer 8

note i=3 starts at 9, not 6: 6 was crossed by 2

Complexity

  • Time — O(n log log n): each prime p performs about n/p markings, and the sum over primes converges to n log log n. Against O(n sqrt n) for trial division.
  • Space — O(n): the boolean array. This is the trade the sieve makes — it buys speed with memory, and at n = 5*10^6 that is a few megabytes. A segmented sieve processes the range in blocks if the array will not fit, which is the answer if the bound grows.

Common Pitfalls

  • Starting the inner loop at 2*i. Correct but wasteful — those multiples are already crossed off, and it changes the constant factor noticeably.
  • Looping the outer index to n rather than stopping at sqrt(n). Also correct, also wasted work.
  • Forgetting that the count is of primes strictly below n, so the array is sized n and index n is never considered.
  • Not marking 0 and 1 as non-prime, which inflates the count by two.
  • Marking multiples of composites. The if sieve[i] guard skips them; without it the work is repeated but the answer is unchanged.

Full Solution — all languages

class Solution:
    def countPrimes(self, n):
        if n < 3:
            return 0
        sieve = [True] * n
        sieve[0] = sieve[1] = False
        i = 2
        while i * i < n:
            if sieve[i]:
                for j in range(i * i, n, i):
                    sieve[j] = False
            i += 1
        return sum(sieve)
Asked at Accenture Citadel
SensAI
Beta
Tap the mic to stop voice mode