Tutorialspoint
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.
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.
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)
ArraysNumberEYSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a boolean array of size n and initialize all values as true except indices 0 and 1
 Step 2: Start with the smallest prime number 2 and mark it as prime
 Step 3: Mark all multiples of 2 starting from 2² as composite (false)
 Step 4: Find the next unmarked number (next prime) and repeat the marking process
 Step 5: Continue this process until we've checked all numbers up to √n
 Step 6: Count all the indices that remain marked as true (prime)
 Step 7: Return the final count of prime numbers

Submitted Code :