欧拉专案#10 Java解决方案无法运作 [英] Project Euler #10 Java solution not working

查看:82
本文介绍了欧拉专案#10 Java解决方案无法运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到质数之和< 2,000,000.这是我在Java中的解决方案,但似乎无法获得正确的答案.请提供一些有关可能出错的信息,并欢迎提供有关代码的一般建议.

I'm trying to find the sum of the prime numbers < 2,000,000. This is my solution in Java but I can't seem get the correct answer. Please give some input on what could be wrong and general advice on the code is appreciated.

打印'sum'给出:1308111344,这是不正确的.

Printing 'sum' gives: 1308111344, which is incorrect.

感谢您的所有帮助.将int更改为long,并且<到< =,并且可以完美地工作,除了查找素数的效率低下:)

Thanks for all the help. Changed int to long and < to <= and it worked flawlessly, except for being an inefficient way of finding prime numbers :)

/*
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
class Helper{
 public void run(){
  Integer sum = 0;
  for(int i = 2; i < 2000000; i++){
   if(isPrime(i))
    sum += i;   
  }
  System.out.println(sum);
 }

 private boolean isPrime(int nr){
  if(nr == 2)
   return true;
  else if(nr == 1)
   return false;
  if(nr % 2 == 0)
   return false;

  for(int i = 3; i < Math.sqrt(nr); i += 2){
   if(nr % i == 0)
    return false;
  }  
  return true;  
 }
}   
class Problem{
 public static void main(String[] args){
  Helper p = new Helper();
p.run();
}
}

推荐答案

结果将太大而无法容纳整数,因此您将获得 BigInteger 或而是改为 long .在这种情况下,一个长就足够了.

The result will be too large to fit into an integer, so you are getting an overflow. Try using a BigInteger or a long instead. In this case a long is enough.

这篇关于欧拉专案#10 Java解决方案无法运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆