我试图从命令行获取两个参数,第一个数字是起点,第二个数字是之后应该找到多少个素数。我需要打印第二个命令参数所说的多次找到的素数。我不知道如何让它运行正确的次数,然后找到素数。这是我尝试过的:
int values = Integer.parseInt(args[0]);
int loopAmount = Integer.parseInt(args[1]);
for (int i = 2; i <= loopAmount; i++) {
loopAmount++;
if (values % i != 0) {
values++;
System.out.println(i);
}
}
最佳答案
你的主循环应该是这样的:
int start = Integer.parseInt(args[0]);
int count = Integer.parseInt(args[1]);
for (int candidate = start, i = 0; i < count; ++candidate) {
if (isPrime(candidate)) {
i++;
System.out.println(candidate);
}
}
我替换了变量名称,使它们更有意义。
在循环内,您必须实现 isPrime
方法:如果它接收的参数是质数,则返回 true
,否则 false
.
关于java - 查找素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35755332/