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
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
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to track count and loop indices
✓ Linear Space
Constraints
- 0 ≤ n ≤ 5 × 106
- Time limit: 1-2 seconds for most test cases
- Consider memory usage for large values of n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code