给定一个数 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
我认为解决这个问题的方法是:
- 写一个isPrime函数来测试这个数是否是素数。
- 写一个可以打印n个素数的函数(int n),
例如n=3,则打印2,3,5三个素数。 - 将所有素数相乘。
但是,我卡在了第二步。 请帮我解决这个问题,或者如果有更好的方法请告诉我。
编辑: 以下是我的代码,到目前为止我只转到第二步。但是当我尝试测试 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。
是素数()
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;
}
关于java - 数的原数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51443158/