- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
#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
Advertisements