Using Sieve of Eratosthenes to find primes JavaScript

In this article, we'll implement the Sieve of Eratosthenes algorithm in JavaScript to efficiently find all prime numbers up to a given limit. This classical algorithm is much faster than checking each number individually for primality.

What is the Sieve of Eratosthenes Algorithm?

The Sieve of Eratosthenes is an ancient and efficient algorithm for finding all prime numbers up to a given range. It works by creating a list of all numbers from 2 to the target number, then systematically eliminating the multiples of each prime number, leaving only the primes.

Sieve of Eratosthenes Process (Finding primes up to 20) Step 1: Mark multiples of 2 2 3 4 5 6 7 Step 2: Mark multiples of 3 2 3 5 7 11 13 Result: Primes up to 20: 2, 3, 5, 7, 11, 13, 17, 19

How the Algorithm Works

The algorithm follows these steps:

  1. Create a boolean array where each index represents a number from 0 to n
  2. Initialize all values to true (assuming all numbers are prime initially)
  3. Mark 0 and 1 as false (they are not prime)
  4. Starting from 2, mark all multiples of each prime as composite (false)
  5. Continue until reaching the square root of n
  6. Collect all remaining true values as prime numbers

Implementation

function sieveOfEratosthenes(n) {
   // Create a boolean array of size n+1
   let primes = new Array(n + 1).fill(true);
   
   // 0 and 1 are not prime numbers
   primes[0] = false;
   primes[1] = false;
   
   // Loop from 2 to square root of n
   for (let i = 2; i <= Math.sqrt(n); i++) {
      if (primes[i]) {
         // Mark all multiples of i as composite
         for (let j = i * i; j <= n; j += i) {
            primes[j] = false;
         }
      }
   }
   
   // Collect all prime numbers
   let result = [];
   for (let i = 2; i <= n; i++) {
      if (primes[i]) {
         result.push(i);
      }
   }
   
   return result;
}

// Example usage
console.log("Prime numbers up to 30:");
console.log(sieveOfEratosthenes(30));

console.log("\nPrime numbers up to 50:");
console.log(sieveOfEratosthenes(50));
Prime numbers up to 30:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Prime numbers up to 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Optimized Version with Count

Here's an enhanced version that also returns the count of prime numbers:

function sieveWithCount(n) {
   let primes = new Array(n + 1).fill(true);
   primes[0] = primes[1] = false;
   
   for (let i = 2; i * i <= n; i++) {
      if (primes[i]) {
         for (let j = i * i; j <= n; j += i) {
            primes[j] = false;
         }
      }
   }
   
   let primeList = [];
   for (let i = 2; i <= n; i++) {
      if (primes[i]) primeList.push(i);
   }
   
   return {
      primes: primeList,
      count: primeList.length
   };
}

// Test the optimized version
let result = sieveWithCount(100);
console.log(`Found ${result.count} prime numbers up to 100:`);
console.log(result.primes);
Found 25 prime numbers up to 100:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Time and Space Complexity

Complexity Type Sieve of Eratosthenes Brute Force Method
Time Complexity O(n log log n) O(n?n)
Space Complexity O(n) O(1)
Efficiency Excellent for ranges Poor for large ranges

Key Advantages

  • Efficient: Much faster than checking each number individually
  • Batch Processing: Finds all primes up to n in one pass
  • Scalable: Performs well for medium to large ranges
  • Simple Logic: Easy to understand and implement

Conclusion

The Sieve of Eratosthenes is an excellent algorithm for finding all prime numbers up to a given limit efficiently. With O(n log log n) time complexity, it significantly outperforms brute force methods, making it ideal for applications requiring multiple prime numbers within a range.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements