JavaScript
Sieve of Eratosthenes
Algorithm
Prime Numbers
Performance Optimization

Sieve of Eratosthenes algorithm in JavaScript running endless for large number

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

The Sieve of Eratosthenes is a classical algorithm used for finding all prime numbers up to a specified integer. It is efficient for large datasets and works by iteratively marking the multiples of each prime number starting from 2. Let's delve into how we can implement this algorithm in JavaScript, and extend it to run endlessly for large numbers by integrating some additional logic.

The Sieve of Eratosthenes Algorithm

Algorithm Explanation

The Sieve of Eratosthenes works with the following steps:

  1. Create a List: Start with a list of integers from 2 to a desired number n .
  2. Assume All Numbers Prime: Assume all numbers in the list are prime.
  3. Iteratively Mark Non-Primes:
    • Start with the first prime number, 2.
    • Mark all multiples of 2 (4, 6, 8, ...) as non-prime.
    • Move to the next number that is still marked as prime (3) and mark all of its multiples.
    • Continue this until we've processed each number up to the square root of n .
  4. Remaining Numbers: All numbers that remain marked as prime are now the list of prime numbers up to n .

JavaScript Implementation

Below is a basic implementation of the Sieve of Eratosthenes in JavaScript:

  • Doubling the Range: Starting with a manageable limit (100), we double it with each iteration, thus simulating an endless computation.
  • Dynamic Delay: Using setTimeout , we introduce a delay between each iteration, balancing CPU load and avoiding unmanageable memory use.
  • Time Complexity: The algorithm complexity is O(nlog(log(n)))O(n \log(\log(n))), making it efficient for generating small to moderately large primes.
  • Space Complexity: The space complexity is O(n)O(n), as we store boolean markers for each number.
  • Memory Management: As the scope increases, consider storing only the found primes externally to reduce memory.
  • Concurrency: JavaScript is single-threaded, but using Web Workers could parallelize marking operations for improved speed.

Course illustration
Course illustration

All Rights Reserved.