Skip to content
Problem 204 · LeetCode 204(opens in a new tab)

Count Primes

MediumArrays

You are given a whole number n. Return how many prime numbers are smaller than n. A prime is a number above 1 whose only divisors are 1 and itself.

n itself does not count, even when it is prime.

Example 1

Input:  n = 12
Output: 5
Why:    the primes below 12 are 2, 3, 5, 7 and 11
2 more examples and the constraints

Example 2

Input:  n = 2
Output: 0
Why:    2 is prime, but it is not below 2

Example 3

Input:  n = 30
Output: 10
Why:    2, 3, 5, 7, 11, 13, 17, 19, 23 and 29

Constraints

  • 0 ≤ n ≤ 5,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Trial divisionO(n√n)
  2. Sieve of EratosthenesO(n log log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 5,000,000Verdict
Trial divisionO(n√n)
Mention it, then move on
Sieve of EratosthenesO(n log log n)
Best; a few passes over an array

n = the input number; every number below it is checked.

Edge cases to test

  • n is 0, 1 or 2. There is no prime below 2, so all three return 0. Guard before making the array, or index 1 does not exist.
  • n is itself prime. Strictly less than: n = 2 gives 0 and n = 10,007 does not count 10,007.
  • n = 3. Only 2 is below it, so the answer is 1. The sieve loop does not even run.
  • The largest n. 5,000,000 has 348,513 primes below it. The sieve handles it in well under a second.

Common mistakes

  • Counting n itself when it is prime. The question asks for primes strictly below n.
  • Starting the crossing-out at 2 × p instead of p × p. It still works, but repeats work.
  • Writing the outer loop as p < n instead of p × p < n, or using p × p ≤ n in a way that overflows a 32-bit int.

How to talk through it

  1. 1Clarify. Strictly below n? What is the largest n? Is 1 prime? (No.)
  2. 2Give trial division. Test each number with divisors up to its root. Say it is about n√n, too slow at 5 million.
  3. 3Flip it to a sieve. Let each prime cross out its multiples, so every number is handled a few times at most.
  4. 4Explain p × p. Smaller multiples were already crossed out by smaller primes, and the outer loop can stop at √n.
  5. 5Test out loud. Run 0, 2, 3 and 12 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?