Prime numbers upto n - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say, we are required to write a JavaScript function that takes in a number, say n, and returns an array containing all the prime numbers upto n.

For example − If the number n is 24, then the output should be −

const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];

Example

Following is the code −

const num = 24;
const isPrime = num => {
   let count = 2;
   while(count < (num / 2)+1){
      if(num % count !== 0){
         count++;
         continue;
      };
      return false;
   };
   return true;
};
const primeUpto = num => {
   if(num < 2){
      return [];
   };
   const res = [2];
   for(let i = 3; i <= num; i++){
      if(!isPrime(i)){
         continue;
      };
      res.push(i);
   };
   return res;
};
console.log(primeUpto(num));

Output

This will produce the following output in console −

[
   2,  3,  5,  7, 11,
   13, 17, 19, 23
]
raja
Published on 18-Sep-2020 12:37:43
Advertisements