Count Primes

Count the prime numbers below n by crossing out the multiples of each prime, the Sieve of Eratosthenes.

Given an integer n, return how many prime numbers are strictly less than n. A prime number is a whole number greater than 1 that only 1 and the number itself divide evenly, like 2, 3, 5 and 7. The input n is between 0 and 5,000,000.

Example 1
Input: n = 10
Output: 4
Explanation: the primes below 10 are 2, 3, 5 and 7.
Example 2
Input: n = 0
Output: 0
Solution

The Idea

Try sharing 7 sweets evenly among 2, 3, 4, 5 or 6 children: every time, some sweets are left over. That is what makes 7 prime. With 6 sweets, 2 or 3 children each get the same amount, so 6 is not prime.

Example 1 asks about the numbers below 10, which means 2 to 9, since 0 and 1 are never prime. Going through them, 4 = 2 × 2, 6 = 2 × 3, 8 = 2 × 4 and 9 = 3 × 3 all split evenly, while 2, 3, 5 and 7 do not. That leaves four primes, the answer 4.

For ten numbers, testing each one is easy. But n can be in the millions, and testing every number on its own repeats the same work again and again: 2 is tried against 4, then against 6, then against 8. Can we use what we learn about 2 just once?

We can, by turning the question around. Instead of asking what divides each number, take each prime and cross out its multiples, since none of them can be prime. Walk up from 2: a number that nobody has crossed out by the time we reach it has no smaller divisor, so it is prime.

Crossing out multiples for n = 10. i = 2 is prime and crosses out 4, 6 and 8. i = 3 is prime and crosses out 9. From i = 4 to 9, the numbers left, 5 and 7, are prime, and their squares 25 and 49 are too big. That leaves 4 primes.

The picture follows this for Example 1, with i as the number we have reached. In the row labelled "start", nothing is crossed out. In the row "i = 2", 2 is still clear, so it is prime, and its multiples 4, 6 and 8 are crossed out in orange.

In the row "i = 3", 3 is clear too, so it is prime. It only needs to cross out 9, because 6 is already gone thanks to 2. In the last row, 4, 6, 8 and 9 are skipped, and 5 and 7 are clear, so they are counted. Their first multiples still worth crossing out, 25 and 49, are too big to matter. The count ends at 4 primes, in teal.

Picking primes out by crossing out multiples like this is called the Sieve of Eratosthenes, after the Greek scholar who described it. Like a kitchen sieve, it lets the multiples fall through and keeps the primes.

Solution Approach

Testing each number on its own gives the right count, but it repeats work. The sieve leaves three choices: where crossing out starts for each prime, when to count a prime, and how to keep the starting point from overflowing.

Testing each number on its own

What would the direct way cost? To check one number k, try every divisor from 2 up to the square root of k. Larger divisors need no check, because if k = a × b and both were above √k, their product would be bigger than k. Each test can take up to √k divisions, so all of them together grow like n √n.

The sieve does less. Each prime crosses out its own multiples once, and numbers that are crossed out cost a single check when the walk reaches them.

Where crossing out starts

Which multiple of a prime is the first one worth crossing out? Take 5 with n = 30. Its multiples 10, 15 and 20 are 5 × 2, 5 × 3 and 5 × 4, and 2 or 3 crossed each of them out earlier. The first multiple with no smaller factor than 5 is 5 × 5 = 25.

The same holds for every prime i. A multiple i × k with k smaller than i also has the smaller factor k, so a prime at or below k has crossed it out already. Crossing out can start at i × i. Some numbers still get crossed out twice: 3 starts at 9 and goes on to 12, which 2 had crossed out before.

When to count a prime

Do we need a second pass over the numbers to count the ones left over? No. When the walk reaches a number that is still clear, it is already certain to be prime. Any number that is not prime has a smallest prime factor p, and the number is at least p × p, so p crossed it out earlier. The count can grow right there.

Keeping i × i inside the int range

Can i × i itself go wrong? With n up to 5,000,000, i goes far past 46,340. Multiplied as int values, 46,340 × 46,340 still gives 2,147,395,600, but 46,341 × 46,341 is too big for an int and comes out as -2,147,479,015.

A negative start passes the check "less than n", and the code then writes into the array at a negative index. Doing the multiplication in long, which holds numbers up to about 9.2 × 1018, gives the true square, and that square is simply larger than n.

Java Solution

The method countPrimes works in these steps:

  1. First, if n is less than 3, return 0. The smallest prime is 2, and "below 2" holds no primes.
  2. Create a boolean array crossedOut with one entry for each number from 0 to n - 1, all false at the start, and a counter count set to 0.
  3. Walk up from 2 with a loop variable i. If crossedOut[i] is true, a smaller prime divides i, so move on.
  4. Otherwise i is prime, so add 1 to count. Then a second loop, inside the first, moves a long variable m from i × i up in steps of i while it is below n, and marks each crossedOut[(int) m] as true. The cast back to int is safe because m is below n.
  5. When i reaches n, return count.

The main method runs both examples, the small inputs 1, 2 and 3 around the first prime, 30 and 100, and 5,000,000, the largest allowed n.

Java
public class CountPrimes {

    public static int countPrimes(int n) {
        if (n < 3) {
            return 0;                         // no prime is smaller than 2
        }
        boolean[] crossedOut = new boolean[n];
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (crossedOut[i]) {
                continue;                     // a smaller prime divides i
            }
            count++;                          // nothing smaller divides i, so i is prime
            // Smaller multiples of i were crossed out already, so start at i * i.
            for (long m = (long) i * i; m < n; m += i) {
                crossedOut[(int) m] = true;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] inputs = {10, 0, 1, 2, 3, 30, 100, 5000000};
        for (int n : inputs) {
            System.out.println("n = " + n + ": " + countPrimes(n));
        }
    }
}

Running it prints:

Output
n = 10: 4
n = 0: 0
n = 1: 0
n = 2: 0
n = 3: 1
n = 30: 10
n = 100: 25
n = 5000000: 348513

Look at n = 2: 0 next to n = 3: 1. The prime 2 only counts once n is above it, because the problem asks for primes strictly less than n. The line n = 30: 10 matches the ten primes 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

The last line, 348,513 primes below 5,000,000, is where the long start matters. A copy of the method with int m = i * i still prints 10 for n = 30. For 5,000,000 it throws ArrayIndexOutOfBoundsException: Index -2146737495 out of bounds for length 5000000.

That index comes from 46,349, the first prime above 46,340. Its square, 2,148,229,801, does not fit in an int and turns into -2,146,737,495, which is below n, so the inner loop uses it.

Complexity

The cost is the walk from 2 to n - 1, plus the crossing out done by each prime.

  • Time: O(n log log n), because each prime p below n crosses out at most n / p multiples, and those amounts added up over all the primes grow like n log log n.
  • Space: O(n), because crossedOut keeps one boolean for every number below n, while the rest is just count and the two loop variables.

The same sieve helps count primes in Prime Arrangements.