Count Primes
Count the prime numbers below n by crossing out the multiples of each prime, the Sieve of Eratosthenes.
Given an integer nnn
Example 1
Output: 4
Explanation: the primes below 10 are 2, 3, 5 and 7.
Example 2
Output: 0
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
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.
The picture follows this for Example 1, with i
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
The same holds for every prime iiiii
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 iiniintint
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 longn
Java Solution
The method countPrimes
- First, if
is less than 3, return 0. The smallest prime is 2, and "below 2" holds no primes.n - Create a
arrayboolean with one entry for each number from 0 to n - 1, allcrossedOut at the start, and a counterfalse set to 0.count - Walk up from 2 with a loop variable
. Ifi iscrossedOut[i] , a smaller prime dividestrue , so move on.i - Otherwise
is prime, so add 1 toi . Then a second loop, inside the first, moves acount variablelong fromm ×i up in steps ofi while it is belowi , and marks eachn ascrossedOut[(int) m] . The cast back totrue is safe becauseint is belowm .n - When
reachesi , returnn .count
The mainn
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:
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: 0n = 3: 1nnn = 30: 10
The last line, 348,513 primes below 5,000,000, is where the longint m = i * inArrayIndexOutOfBoundsException: 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 intn
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
crosses out at most n / p multiples, and those amounts added up over all the primes grow like n log log n.n - Space: O(n), because
keeps onecrossedOut for every number belowboolean , while the rest is justn and the two loop variables.count
The same sieve helps count primes in