Primorial of a number in C++


In this problem, we are given a number n. Our task is to print its primorial number.

Primorial number (Pn#) is a number that is the product of first n prime numbers.

Primorial number is similar to factorial of a number n. The difference is that factorial can be any number but in case of primorial number, all prime numbers are used.

Let’s take an example to understand the problem,

Input: N = 4
Output
210
Explanation: Primorial number, Pn# = 2 * 3 * 5 * 7 = 210

To solve this problem, we have to find the first n prime numbers. Print the product of all prime numbers upto n which is the value of primorial numbers.

Example

Program to show the implementation of our solution,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000000;
vector <int> primeNumbers;
void findPrimes() {
   bool marked[MAX/2 + 1] = {0};
   for (int i = 1; i <= (sqrt(MAX)-1)/2 ; i++)
      for (int j = (i*(i+1))<<1 ; j <= MAX/2 ; j += 2*i +1)
         marked[j] = true;
   primeNumbers.push_back(2);
   for (int i=1; i<=MAX/2; i++)
      if (marked[i] == false)
         primeNumbers.push_back(2*i + 1);
}
int findPrimorial(int n) {
   findPrimes();
   int result = 1;
   for (int i=0; i<n; i++)
   result = result * primeNumbers[i];
   return result;
}
int main() {
   int N = 6;
   cout<<"Primorial(P#) of first "<<N<<" prime numbers is "<<findPrimorial(N)<<endl;
   return 0;
}

Output

Primorial(P#) of first 6 prime numbers is 30030

Updated on: 03-Feb-2020

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements