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?
My solution:
You need to test the number against every prime less than its square root to ensure it is prime.
You're only testing against 2,3 and 5.
Because storing all the primes is not always space-feasable, a common technique is to test for 2, and then test all odd numbers starting at 3. This requires a loop.
consider:
boolean isPrime(long n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
if (n < 9) return true;
if (n % 3 == 0) return false;
long max = (long)(Math.sqrt(n + 0.0)) + 1;
for (int i = 5; i <= max; i += 6) {
if (n % i == 0) return false;
if (n % (i + 2) == 0) return false;
}
return true;
}