
Problem
Solution
Submissions
Count Primes
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to count the number of prime numbers less than a given non-negative integer n using the Sieve of Eratosthenes algorithm. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Example 1
- Input: n = 10
- Output: 4
- Explanation:
- We need to find prime numbers less than 10: [2, 3, 5, 7].
- Number 2 is prime, 3 is prime, 4 is not prime (2×2), 5 is prime.
- Number 6 is not prime (2×3), 7 is prime, 8 is not prime (2×4), 9 is not prime (3×3).
- Therefore, there are 4 prime numbers less than 10.
- We need to find prime numbers less than 10: [2, 3, 5, 7].
Example 2
- Input: n = 0
- Output: 0
- Explanation:
- There are no numbers less than 0.
- Therefore, the count of prime numbers is 0.
- The result is 0.
- There are no numbers less than 0.
Constraints
- 0 ≤ n ≤ 5 × 10^6
- You must use the Sieve of Eratosthenes algorithm
- Time Complexity: O(n log log n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Create a boolean array of size n and initialize all values as true
- Start with the first prime number 2 and mark all its multiples as composite
- Find the next unmarked number and repeat the process
- Continue until you've processed all numbers up to √n
- Count all the numbers that remain marked as prime