我有下面的程序,我试图找到前 1000 个素数的总和。在代码中,解决方案 1 和 2 有什么区别?为什么我不应该将 count 变量放在 if 条件之外?如果我将变量放在 if 之外,我显然没有得到我需要的答案,但我不明白为什么它在逻辑上是错误的。这可能是一件简单的事情,但我无法弄清楚。请高手帮忙。
解决方案1:
public class SumOfPrimeNumbers {
public static void main(String[] args) {
long result = 0;
int number = 2;
int count = 0;
while (count < 1000) {
if (checkPrime(number) == true) {
result = result + number;
count++;
}
number++;
}
System.out.println("The sum of first 1000 prime numbers is " + result);
}
public static boolean checkPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
解决方案2:
public class SumOfPrimeNumbers {
public static void main(String[] args) {
long result = 0;
int number = 2;
int count = 0;
while (count < 1000) {
if(checkPrime(number)==true)
{
result = result + number;
}
count++; //The count variable here has been moved to outside the loop.
number++;
}
System.out.println("The sum of first 1000 prime numbers is "+ result);
}
public static boolean checkPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}