简体   繁体   中英

CodeEval Sum of the first 1000 prime numbers in java

Now I am trying to do an easy task from https://www.codeeval.com

Where you need to find the sum of first 1000 prime numbers. I done it in IDEA and my sum is same with correct answer. But when i try to upload my file to site it show error after loading:

"CodeEval Error: Compilation was aborted after 10 seconds".

I have no idea about this error. Any ideas about this error?

    public class solution {
        public static void main(String[] args) {
           int sum = 2;
           int num = 3;
           for (int i = 2; i <= 1000; i++) {
               while (!IsPrime(num)) {
                   num += 1;
               }
               sum = sum + num;
               num += 1;
           }
           System.out.println(sum);
        }
        static boolean IsPrime(int TestNum) {
            int NumOfDividers = 1;
            for (int x = 2; x <= TestNum; x++) {
                if (TestNum % x == 0) {
                    NumOfDividers = NumOfDividers + 1;
                }
            }
            return (NumOfDividers == 2);
    }
}

The simplest optimisation for your isPrime method is to skip most of the divisions like this:

static boolean isPrime(long n) {
    if (n != 2 && (n & 1) == 0) {
        // Early test for even.
        return false;
    }
    for (long i = 3; i <= n / i; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

It is possible to improve on this using a list of known primes but that is probably not what you are looking for.

CodeEval Java support has been acting up lately. I usually have to upload my solutions multiple times, because sometimes it will score them appropriately and sometimes fail on the error you mention. Try that, and then delete the ones it times out on. Not that you can't improve your solution, but I would say that that's not why you're getting that error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM