Java solution to Project Euler Problem 7

Problem 7:

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 10001st prime number?

Running time: 10010ms (10 sec)

Assessment: This is a classic example of a bad factorization algorithm, because the results aren’t memoized in any way. I promise my solutions get a lot better right around Problem 21.

4 thoughts on “Java solution to Project Euler Problem 7

  1. for less complexity you can use

    public class Problem7{ private static boolean isPrime(long n){ if(n%2==0&&n!=2) return false; for(long i=3;i<=Math.sqrt(n)+1;i+=2){ if(n%i==0) return false; } return true; } public static void main(String[] args){ long begin=System.currentTimeMillis(); int NumPrimes=2; long i=3; while(NumPrimes<=10001){ if(isPrime(i)){ i+=2; NumPrimes++; } else i+=2; } long end = System.currentTimeMillis(); System.out.println(i-2); System.out.println(end-begin + "ms"); } }

  2. ther is a small error in this code …instead of stopping at PRIME NO. 10001 ..the while loop run one time more than the required..
    So to get the accurate answer ..plz put this line of code in “if(isPrime(i))”






Leave a Reply

Your email address will not be published. Required fields are marked *