Given a number n, the task is to calculate its primorial. Primorial (denoted as Pn#) is product of first n prime numbers. Primorial of a number is similar to factorial of a number. In primorial, not all the natural numbers get multiplied only prime numbers are multiplied to calculate the primorial of a number. It is denoted with P#.
Examples:
Input: n = 3
Output: 30
Priomorial = 2 * 3 * 5 = 30
As a side note, factorial is 2 * 3 * 4 * 5
Input: n = 5
Output: 2310
Primorial = 2 * 3 * 5 * 7 * 11
The way I think to solve this problem is:
However, I am stuck into the step two. Please help me to solve this problem, or if there is any better way, please tell me.
edit: following is my code, I just go to the step two so far. But when I try to test the countPrime function, the output is 0.
public class PrimorialNum {
static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return true;
}
}
return false;
}
static int countPrime(int k) {
int count = 0;
int x=0;
while (x >= 2) {
if (isPrime(x)) {
count++;
}
x++;
System.out.println(x);
}
return count;
}
public static void main(String[] args) {
System.out.println(countPrime(2));
}
}
I think this might work for you, did not have the possibility to try it myself right now. If k > 0.
isPrime()
static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0 && i != n) return false;
}
return true;
}
2.Just print
static void countPrime(int k) {
int x = 2;
int primesFound = 0;
while (primesFound != k) {
if (isPrime(x)) {
System.out.print(x);
primesFound++;
}
x++;
}
}
3.Multiply
static int countPrime(int k) {
int count = 2;
int x = 3;
int primesFound = 1;
while (primesFound != k) {
if (isPrime(x)) {
count = count * x;
primesFound++;
}
x++;
}
return count;
}