Count Primes – Solution & Complexity
Solution Walkthrough
Step 1: Understand the Pattern
- We need every prime below
n, not includingnitself. - Checking each number independently repeats a lot of work.
- A sieve marks composite numbers once and counts what remains.
- We need every prime below
Step 2: Handle the Tiny Cases
- If
nis0,1, or2, there are no primes below it. - Return
0immediately for those inputs. - This also lets the sieve assume
n >= 3.
- If
Step 3: Sieve of Eratosthenes
- Assume every number from
2ton-1is prime. - For each prime
p, cross out its multiples starting atp * p. - Anything still marked prime at the end is counted.
- Assume every number from
Step 4: Final Solution and Complexity
- Starting at
p * pis safe because smaller multiples were already crossed out by smaller primes. - Time complexity is
O(n log log n). - Space complexity is
O(n)for the boolean sieve.
- Starting at