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.

Input & Output

Example 1 — Small Range
$ Input: n = 10
Output: 4
💡 Note: Primes less than 10 are [2, 3, 5, 7], so count = 4
Example 2 — Very Small Range
$ Input: n = 2
Output: 0
💡 Note: No primes less than 2, so count = 0
Example 3 — Edge Case
$ Input: n = 3
Output: 1
💡 Note: Only prime less than 3 is [2], so count = 1

Constraints

  • 0 ≤ n ≤ 5 × 106

Visualization

Tap to expand
Count Primes - Sieve of Eratosthenes INPUT Numbers from 0 to n-1 (n=10) 0 1 2 3 4 5 6 7 8 9 Prime Not Prime Input: n = 10 Find primes less than n Range: [2, 9] ALGORITHM STEPS 1 Create Boolean Array isPrime[0..n-1] = true 2 Mark 0, 1 as Not Prime isPrime[0] = isPrime[1] = false 3 Sieve Multiples For i=2 to sqrt(n): Mark i*i, i*i+i, ... false 4 Count Remaining Count true values in array Sieve Process: i=2: mark 4,6,8 false i=3: mark 9 false Remaining: 2,3,5,7 Count = 4 primes FINAL RESULT Prime numbers less than 10: 2 3 5 7 Output: 4 OK - 4 primes found Verification: 2 (prime), 3 (prime) 5 (prime), 7 (prime) Total: 4 primes Key Insight: The Sieve of Eratosthenes eliminates composite numbers by marking multiples of each prime. Starting from i*i (not 2*i) is an optimization since smaller multiples are already marked. Time Complexity: O(n log log n) | Space Complexity: O(n) TutorialsPoint - Count Primes | Sieve of Eratosthenes Approach
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
125.0K Views
Medium Frequency
~15 min Avg. Time
5.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