#204

Count Primes

Medium Sieve of Eratosthenes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count the prime numbers strictly less than n.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many primes are below n (n up to 5 million)?

Why this works: instead of testing each number, cross out the multiples of each prime. Every composite gets crossed out by its smallest prime factor.

Example: n = 10

start: 2 3 4 5 6 7 8 9p=2: cross 4, 6, 8p=3: cross 9left: 2 3 5 7 → 4 primes

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Starting the inner loop at 2 * p (still correct, just slower) or using int for p * p, which can overflow — use p <= n / p or a long.