我几个小时以来一直在修补这些代码,而我却无法输出正确的答案。谁能告诉我哪里出错?此版本正在输出104033
package Euler;
public class prime100001 {
private static boolean isPrime(long num) {
if (num == 2 || num == 3){
return true;
}
if (num % 2 == 0){
return false;
}
for (int i = 3; i * i < num; i += 2){
if (num % i == 0){
return false;
}
}
return true;
}
public static void main (String [] args){
int counter = 0;
int primenum = 1;
while(counter < 10001){
primenum += 2;
if(isPrime(primenum)){
counter ++;
}
}
System.out.println(primenum);
}
}
答案 0 :(得分:0)
只是想确定,你想打印10,001个素数吗?
public class prime100001 {
private static boolean isPrime(long num) {
if (num == 2 || num == 3){
return true;
}
if (num % 2 == 0){
return false;
}
for (int i = 3; (i * i) <= num; i += 1){
// Changed the condition from < to <=, as you need to capture squares
// (e.g. when num = 9, original method will return false as i * i = 9 < 9 is false.
// Also changed the increment from 2 to 1.
if (num % i == 0){
return false;
}
}
return true;
}
public static void main(String [] args){
int counter = 0;
int lastPrime = 1;
while(counter < 10001){
lastPrime += 1;
// Changed increment to include 2 in the count, plus
// not skipping any other ints to test.
if (isPrime(lastPrime)){
counter++;
}
}
System.out.println(lastPrime);
// Shows 104,743
// 10,000th prime: https://primes.utm.edu/lists/small/10000.txt
}
}
希望这会有所帮助。 ;)