Using Sieve of Eratosthenes to find primes JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number, say n.

The function should return an array of all the prime numbers between 1 and n.

Approach

The first step is to create an array as large as the given number, with all its values initialized as true. The array indexes will represent all the possible prime numbers, with all being true at the beginning.

Then, we create a for loop that iterates from 2 to the square root of the given number. By definition, products of any integer cannot be prime, while 0 and 1 are ignored because divisibility by them does not affect primality.

Lastly, we can simply filter out all the false values to arrive at all the prime numbers.

Example

const num = 100;
const findPrimes = (num = 10) => {
   const numArr = new Array(num + 1);
   numArr.fill(true);
   numArr[0] = numArr[1] = false;
   for (let i = 2; i <= Math.sqrt(num); i++) {
      for (let j = 2; i * j <= num; j++){
          numArr[i * j] = false;
      }
   }
   return numArr.reduce((acc, val, ind) => {
      if(val){
         return acc.concat(ind);
      }else{
         return acc;
      };
   },[]);
};
console.log(findPrimes(num));

Output

And the output in the console will be −

[
   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
]
raja
Published on 25-Nov-2020 05:51:13

Advertisements