Horje
JavaScript Program for Sieve of Eratosthenes

In this article, we will be demonstrating a JavaScript program for the Sieve of Eratosthenes algorithm.

The Sieve of Eratosthenes algorithm is an efficient way of getting all the prime numbers that exist in the given range e.g.,

Input: n =10
Output: 2 3 5 7 
Input: n = 20 
Output: 2 3 5 7 11 13 17 19

Approach

The programmatic approach for the algorithm is as follows:

  • First, create a boolean array of length n+1 named prime with all values true
  • Assign false for index 0 and 1 as these numbers are non-prime.
  • The first prime number is 2, so start iterating from index 2 and assign all multiples of 2 as false to represent them as non-prime.
  • Similarly, check for remaining indexes If true make all it’s multiple as false and continue till the loop ends i.e. i <= n.
  • After this iterate the array store the indexes for which the prime value is true and return the output array.

Example: In this example, we will print all prime numbers up to the number 20.

Javascript

function sieveOfEratosthenes(n) {
  
    // Create boolean array and fill true
    let prime = new Array(n + 1).fill(true);
      
    // Make mulltiples of prime number false
    for (let i = 2; i <= n; ++i) {
        if (prime[i])
            for (j = i * i; j < n + 1; j += i) {
                prime[j] = false;
            }
    }
      
    // Extract all indexes for true values
    primeArray = prime.reduce((acc, e, i) => {
        if (e == true && i >= 2) {
            acc.push(i);
        }
        return acc;
    }, []);
    // Return resultant array
    return primeArray;
}
  
// Input number
const num = 40;
  
// Call function and show output
console.log("Prime numbers up to "+ num+": "+ sieveOfEratosthenes(num));

Output

Prime numbers up to 40: 2,3,5,7,11,13,17,19,23,29,31,37


Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Program for Binary Search using Recursion JavaScript Program for Binary Search using Recursion
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array
Applications of Recursion in JavaScript Applications of Recursion in JavaScript
JavaScript Program for Selection Sort JavaScript Program for Selection Sort
JavaScript Program for Insertion Sort JavaScript Program for Insertion Sort

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13