How can I improve this code for Project Euler 7?

后端 未结 4 658
悲哀的现实
悲哀的现实 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:01

    The following solution checks only the odd numbers to be prime, but it counts 2 as prime from the beginning:

    public class A {
    
        static int N = 10001;
    
        private static boolean isOddPrime(long x) {
    
            for ( int i = 3 ; i*i <= x ; i+=2 ) {
                if ( x % i == 0 ) {
                    return false;
                }               
            }
            return true;
        }
    
        public static void main(String[] args) throws Exception {
            long start = System.nanoTime();
            int x;
            int i = 2;      // 3 is the 2nd prime number
            for ( x = 3 ; ; x+=2 ) {
                if ( isOddPrime(x) ) {              
                    if ( i == N )
                        break;
                    i++;
                }
            }
            System.out.println(x);
    
            long stop = System.nanoTime();
            System.out.println("Time: " + (stop - start) / 1000000 + " ms");
        }
    }
    

    Output:

    104743
    Time: 61 ms
    

提交回复
热议问题