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 Problem: Count primes less than nInput: n = 1010Find all primes < 102357Primes found: [2, 3, 5, 7]Count the primes4Output: 4 primes less than 10
Understanding the Visualization
1
Input
Given n = 10, find primes < 10
2
Process
Use sieve to identify primes: 2, 3, 5, 7
3
Output
Count = 4 primes found
Key Takeaway
🎯 Key Insight: Use sieve to mark composites instead of testing each number individually
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