简体   繁体   English

CodeEval Java中前1000个质数的总和

[英]CodeEval Sum of the first 1000 prime numbers in java

Now I am trying to do an easy task from https://www.codeeval.com 现在,我正在尝试从https://www.codeeval.com做一个简单的任务

Where you need to find the sum of first 1000 prime numbers. 需要查找前1000个质数之和的位置。 I done it in IDEA and my sum is same with correct answer. 我在IDEA中完成此操作,总和与正确答案相同。 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: isPrime方法最简单的优化是跳过大部分这样的划分:

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. CodeEval Java支持最近已经发挥作用。 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. 并不是说您不能改善解决方案,而是要说这不是为什么您会收到该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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