I am attempting problem 7 on Project Euler. I have come up with this solution which works fine for finding smaller nth prime numbers, but really lags when it comes to higher nth prime numbers. I am not quite sure where to start to make it more efficient.
public class TenThousandFirstPrime {
public static boolean isPrime(int num) {
if(num % 2 == 0) return false;
for(int i = 3; i < Math.floor(Math.sqrt(num)); i += 2) {
if(num % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
int count = 2;
int i = 3;
while(count <= 10001) {
if(isPrime(i)) {
i += 2;
count++;
}
}
System.out.println(i);
}
}
The solution only took a couple of minutes and I didn't expect it to be as slow as it is...
i += 2;
, probably because you've eliminated all multiples of 2 from the possible prime numbers. Why only for 2? Why not take that to its logical conclusion, and eliminate all multiples of every prime number you find? That's what the Sieve of Eratosthenes does - you should look into that if you want a faster prime number generator. \$\endgroup\$