Find the primorial of numbers - JavaScript


The primorial of a number n is equal to the product of first n prime numbers.

For example, if n = 4

Then, the output primorial(n) is,

2*3*5*7 = 210

We are required to write a JavaScript function that takes in a number and returns its primordial.

Example

Following is the code −

const num = 4;
const isPrime = n => {
   if (n===1){
      return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const primorial = num => {
   if(num === 0){
      return 0;
   }
   let count = 1, flag = 3;
   let prod = 2;
   while(count < num){
      if(isPrime(flag)){
         prod *= flag;
         count++;
      };
      flag++;
   };
   return prod;
};
console.log(primorial(num));

Output

Following is the output in the console −

210

Updated on: 16-Sep-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements