给定一个数字n,任务是计算它的原初。原生(表示为 Pn#)是前 n 个素数的乘积。数的原初与数的阶乘类似。在原初中,并不是所有的自然数都相乘,只有素数相乘才能计算一个数的原初。用 P# 表示。
示例:
Input: n = 3
Output: 30
Priomorial = 2 * 3 * 5 = 30
顺便说明一下,阶乘是 2 * 3 * 4 * 5
Input: n = 5
Output: 2310
Primorial = 2 * 3 * 5 * 7 * 11
我认为解决这个问题的方法是:
但是,我陷入了第二步。 请帮我解决这个问题,或者如果有更好的方法,请告诉我。
编辑: 以下是我的代码,到目前为止我只进行了第二步。但是当我尝试测试 countPrime 函数时,输出为 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));
}
}
我认为这可能对你有用,但现在无法亲自尝试。如果 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.只需打印
static void countPrime(int k) {
int x = 2;
int primesFound = 0;
while (primesFound != k) {
if (isPrime(x)) {
System.out.print(x);
primesFound++;
}
x++;
}
}
3.乘法
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;
}
Scanner scan = new Scanner (System.in);
System.out.print ("");
int num = scan.nextInt();
long primorial = 1, faktor = 1;
while ( num != 0)
{
faktor ++;
boolean isPrime = true;
for (int i = 2; i < faktor; i++)
{
if (faktor % i==0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
num--;
primorial *= faktor;
}
}
System.out.print (primorial);
import java.util.Scanner;
class Primorial {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter number who's Primorial is to be found");
int n= sc.nextInt();
int i=2,primo=1,count=0,q;
while(n>0)
{
for(q=1;q<=i;q++)//check for prime
if(i%q==0)
count++;
if(count==2)
{
primo=primo*i;//multiply if prime
n--;//decrease n when once multiplied to keep track
}
i++;
count=0
}
System.out.println(primo);
}
}