How to usethe Optimized Sieve of Eratosthenes Algorithm in Javascript
The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given number by eliminating multiples of each prime iteratively.
Example: In this example we are using the optimized Sieve of Eratosthenes algorithm to find and print prime numbers within the user-provided interval, efficiently identifying primes and displaying them.
Javascript
function sieveOfEratosthenesOptimized(start, end) { const primes = new Array(end + 1).fill( true ); primes[0] = primes[1] = false ; for (let i = 2; i * i <= end; i++) { if (primes[i]) { for (let j = i * i; j <= end; j += i) { primes[j] = false ; } } } for (let i = Math.max(2, start); i <= end; i++) { if (primes[i]) console.log(i); } } // Take input from the user using prompt const startInterval = 10; const endInterval = 20; // Execute the function with user-provided interval console.log( "Prime numbers between" , startInterval, "and" , endInterval, "(Sieve of Eratosthenes - Optimized):" ); sieveOfEratosthenesOptimized(startInterval, endInterval); |
Prime numbers between 10 and 20 (Sieve of Eratosthenes - Optimized): 11 13 17 19
JavaScript Program to Print All Prime Numbers in an Interval
In this article, we will explore a JavaScript program to find and print all prime numbers within a given range. A prime number is a natural number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23…, The program efficiently identifies and displays prime numbers within the specified range.
There are several methods that can be used to Print All Prime Numbers in an Interval.
- Using Trial Division Method
- Optimized Solution
- Using the Sieve of Eratosthenes” algorithm
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us