Counting prime numbers from 2 upto the number n JavaScript

We are required to write a JavaScript function that takes in a number, say n, as the first and the only argument.

The function should then return the count of all the prime numbers from 2 up to the number n (exclusive).

For example:

For n = 10, the output should be: 4 (2, 3, 5, 7)
For n = 1, the output should be: 0

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, etc.

Using Sieve of Eratosthenes Algorithm

The most efficient approach is to use the Sieve of Eratosthenes algorithm, which marks all composite numbers and counts the remaining prime numbers:

const countPrimesUpto = (num = 1) => {
    if (num  b + a) - 2;
};

console.log(countPrimesUpto(35));
console.log(countPrimesUpto(6));
console.log(countPrimesUpto(10));
11
3
4

How the Algorithm Works

The function works by creating an array where each index represents a number, and the value indicates whether it's prime (1) or composite (0):

  1. Create an array filled with 1s (assuming all numbers are prime initially)
  2. Start from 2 and mark all its multiples as composite (0)
  3. Move to the next unmarked number and repeat
  4. Count the remaining prime numbers by subtracting 2 (for indices 0 and 1)

Step-by-Step Example

Let's trace through the algorithm for n = 10:

const countPrimesUpto = (num) => {
    if (num  b + a) - 2;
    console.log(`Prime count: ${count}`);
    return count;
};

countPrimesUpto(10);
Initial array: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Marking multiples of 2:
Array after marking: [1, 1, 1, 1, 0, 1, 0, 1, 0, 1]
Marking multiples of 3:
Array after marking: [1, 1, 1, 1, 0, 1, 0, 1, 0, 0]
Prime count: 4

Alternative Simple Approach

For smaller numbers, you can use a simpler prime checking function:

function isPrime(n) {
    if (n 

4
11

Performance Comparison

Method Time Complexity Space Complexity Best For
Sieve of Eratosthenes O(n log log n) O(n) Large numbers
Simple Prime Check O(n?n) O(1) Small numbers

Conclusion

The Sieve of Eratosthenes is the most efficient algorithm for counting prime numbers up to n. It uses more memory but provides better performance for larger numbers compared to checking each number individually.

Updated on: 2026-03-15T23:19:00+05:30

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements