Thursday, 8 August 2013

Project Euler #7 Java code not working

Project Euler #7 Java code not working

I've been working on Project Euler #7, and can't figure out why my program
is not working. The problem is as follows:
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?
This is my program so far:
public class Euler7 {
public static void main (String[] args) {
long count = 1;
long primes = 0;
while (primes <= 10001) {
if (isPrime(count)){
primes++;
if (primes == 10001) {
System.out.println(count);
}
}
count++;
}
}
public static boolean isPrime (long i) {
if (i <= 1) return false;
else if (i == 2 || i == 3) return true;
else if (i % 2 == 0 || i % 3 == 0) return false;
else {
for (int n = 3; n < Math.sqrt(i); n+=2) {
if (i % n == 0) {
return false;
}
}
return true;
}
}
}

No comments:

Post a Comment