How can I improve this code for Project Euler 7?

后端 未结 4 660
悲哀的现实
悲哀的现实 2021-01-27 02:29

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:



        
4条回答
  •  迷失自我
    2021-01-27 03:17

    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;
    }
    

提交回复
热议问题