我的问题与以下代码有关:
public static void main(String[] args) {
// Find Prime Numbers from 0 to 100
int i;
for (i=2; i <= 100; i++) {
int j = 2;
boolean iPrime = true;
//The following line gives incorrect results, but should execute faster
// while ((iPrime = true) && (j < (i / 2 + 1))) {
//The following line gives correct results but performs un-necessary operations
//by continuing to calculate after the number is found to be "not prime"
while (j < (i / 2 + 1)) {
j++;
if ((i % j) == 0) {
iPrime = false;
//System.out.println(j + " is a factor of " + i);
}
}
if (iPrime) {
System.out.println(i + " is a prime number!");
}
}
}
现在,正如我在代码中所评论的那样,我想要实现的是通过仅在iPrime = true时执行’while’循环来更快地执行我的程序. 50%的数字可被2整除,因此一旦确定,计算就可以停止.
我正在从一本书中做这个项目作为初学者’例子的一部分’,我实际上是想尽可能快地计算高达1000000只是因为我自己的“额外信用”……
我读到了“短路”和“运算符”&&如果前半部分为真,则仅评估语句的后半部分,如果为假,则两者不相互评估(节省CPU)
它也将退出循环,这将节省更多的CPU ……
但由于某种原因,它无法正常工作!我在整个过程中添加了更多的System.out.println()语句,列出了’iPrime’是什么 – 输出是奇怪的……它打开和关闭iPrime并评估每个数字,这是我无法理解的.