【发布时间】:2012-06-07 21:35:30
【问题描述】:
我正在尝试解决 Project Euler 的第 10th 个问题,但由于某种原因我无法正确解决。我在编程和 Java 方面真的很陌生,所以我不明白为什么它不起作用。问题的重点是求所有小于 2,000,000 的素数之和。
/* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
public static void main(String[] args){
long n = 1;
long sum = 0;
long limit;
System.out.println("Enter the limit of n: ");
limit = TextIO.getlnLong(); //TextIO is another input method
while (limit <= 0){
System.out.println("Enter the limit of n (must be positive): ");
limit = TextIO.getlnLong();
}
while (n < limit){
n++;
if (n % 2 != 0 && n % 3 != 0 && n % 5 != 0 && n % 7 != 0 && n != 1 || n == 2 || n == 3 || n == 5 || n == 7){ //this is my prime checking method, might be flawed
sum = sum + n;
System.out.println(+sum);
} //end if
}//end while
System.out.println("The sum of the primes below 2,000,000 is: " +sum);
} //end of main
【问题讨论】:
-
你的素数检查方法肯定有缺陷。
-
我还建议将素数检出分解为单独的方法。
-
这是一个经过验证的Sieve,您可以使用。
-
121 = 11*11。那不是素数……完美的正方形,是的。
-
每当您在 SO 上发帖时,请非常清楚地说明您的问题。尽管人们可以编译和运行代码并看到您发布的问题,但最好清楚地指出您的程序是否没有编译或者您得到了一些不正确的答案。尽管在您的情况下,许多人指出的有缺陷的逻辑很容易被抓住。
标签: java