JavaScript function to take a number n and generate an array with first n prime numbers


We are required to write a JavaScript function that takes in a number n and returns an array that contains first n prime numbers. We know that prime numbers are those numbers that are only divisible by 1 and themselves like 2, 3, 19, 37, 73 etc.

We will first write a function that checks whether a given number is prime or not and then run a loop to generate n prime numbers. The code to check for prime numbers −

const isPrime = (n) => {
   for(let i = 2; i <= n/2; i++){
      if(n % i === 0){
         return false;
      }
   };
   return true;
};

And the full generating code will be −

Example

const isPrime = (n) => {
   for(let i = 2; i <= n/2; i++){
      if(n % i === 0){
         return false;
      }
   };
   return true;
};
const generatePrime = num => {
   const arr = [];
   let i = 2;
   while(arr.length < num){
      if(isPrime(i)){
         arr.push(i);
      };
      i = i === 2 ? i+1 : i+2;
   };
   return arr;
};
console.log(generatePrime(6));
console.log(generatePrime(16));
console.log(generatePrime(36));

Output

The output in the console will be −

[ 2, 3, 5, 7, 11, 13 ]
[
   2, 3, 5, 7, 11, 13,
   17, 19, 23, 29, 31, 37,
   41, 43, 47, 53
]
[
   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, 101, 103,
   107, 109, 113, 127, 131, 137, 139, 149, 151
]

Updated on: 28-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements