求第10001个素数
/**
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
* see that the 6th prime is 13.
*
* What is the 10 001st prime number?
*/
代码:
private static int nthPrime(int N) {
if (N == 1)
return 2;
int k = 1;
while (--N > 0) {
k = k + 2;
while (!isPrime(k))
k = k + 2;
}
return k;
}
private static boolean isPrime(int n) {
if (n % 2 != 0)
for (int i = 3; i <= Math.sqrt(n); i = i + 2) {
if (n % i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(nthPrime(10001));
}
思想:除了使步长为2,我已经不会优化了。。。