Count Primes - Problem

Given an integer n, return the number of prime numbers that are strictly less than n.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 are the first few prime numbers.

Your task is to efficiently count how many such prime numbers exist below a given threshold n.

Example: If n = 10, the prime numbers less than 10 are: 2, 3, 5, 7. So the answer is 4.

Input & Output

example_1.py — Small Range
$ Input: n = 10
Output: 4
💡 Note: Prime numbers less than 10 are: 2, 3, 5, 7. Count = 4.
example_2.py — Edge Case
$ Input: n = 2
Output: 0
💡 Note: No prime numbers are less than 2.
example_3.py — Larger Range
$ Input: n = 20
Output: 8
💡 Note: Prime numbers less than 20 are: 2, 3, 5, 7, 11, 13, 17, 19. Count = 8.

Visualization

Tap to expand
Sieve of Eratosthenes - Batch Elimination2345678910✓ Green: Prime Numbers✗ Red: Eliminated (Multiples)Efficiency ComparisonBrute Force: Check each number individually• Test 2: check divisors 1,2 → prime• Test 3: check divisors 1,2,3 → prime• Test 4: check divisors 1,2,3,4 → not prime (4÷2=2)Sieve: Eliminate in batches• Found prime 2 → eliminate 4,6,8,10,12...• Found prime 3 → eliminate 9,15,21,27...• Much fewer operations overall!Time Complexity ImprovementBrute Force: O(n√n) → Sieve: O(n log log n)For n=1,000,000: ~31,623 vs ~693 operations!
Understanding the Visualization
1
Initialize Grid
Create array marking all numbers 2 to n-1 as potentially prime
2
Process Prime 2
Keep 2 as prime, eliminate all even numbers (4,6,8,10,...)
3
Process Prime 3
Keep 3 as prime, eliminate remaining multiples (9,15,21,...)
4
Continue Pattern
Repeat for each unmarked number up to √n
5
Count Results
Sum up all numbers that remain unmarked
Key Takeaway
🎯 Key Insight: The Sieve of Eratosthenes transforms an O(n√n) problem into O(n log log n) by eliminating composites in systematic batches rather than testing each number individually.

Time & Space Complexity

Time Complexity
⏱️
O(n√n)

For each of n numbers, we check up to √n potential divisors

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to track count and loop indices

n
2n
Linear Space

Constraints

  • 0 ≤ n ≤ 5 × 106
  • Time limit: 1-2 seconds for most test cases
  • Consider memory usage for large values of n
Asked in
Amazon 45 Microsoft 38 Google 32 Adobe 28
67.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen