我知道新手的问题,但我不知道这个问题的代码中有什么错误。这个问题要求得到2,000,000以下的所有素数之和。
我不明白为什么我的代码适用于较小的集合,但是当我耐心地等待我的代码完成200万次的时候,它会吐出一个错误的答案。本案为1 179 908 154人。
免责声明--我意识到我编写的代码非常低效/浪费,我应该使用Eratosthenes的筛子和其他东西。我只是想弄清楚为什么会给出错误的答案。
public static void main(String args[]) {
int[] primes = new int[2000000];
int index=0;
int ans=0;
//finding primes and populating array
for (int candidate=2; candidate<=2000000; candidate++) {
System.out.println(candidate); //so I can watch the numbers go up
for (int divisor=1; divisor<=candidate; divisor++) {
if (candidate%divisor==0 && candidate==divisor) {
primes[index]=candidate;
index++;
break;
}
if (candidate%divisor==0 && candidate!=divisor && divisor!=1) {
break;
}
}
}
//adding primes
for (int m=0; m<primes.length; m++) {
ans+=primes[m];
}
System.out.println(ans);
}发布于 2020-09-23 03:05:34
我认为您的问题在于ans的类型。
在Java中,ints有4个字节长,这意味着它们只能存储从-2,147,483,648到2,147,483,647不等的数字。二百万以下的素数之和远大于这些值。这里发生的是int变量溢出并“转”(它“跳过”从最大值到最小值)。
尝试将ans类型更改为long。
发布于 2020-09-23 03:10:21
在将Java程序加载到本地Scala中时,我得到了相同的错误结果。
scala> org.oeis.primes.PrimeLister.listPrimes(2_000_000)
res3: java.util.ArrayList[Integer] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, ...
scala> import collection.JavaConverters._
import collection.JavaConverters._
scala> res3.asScala
^
warning: object JavaConverters in package collection is deprecated (since 2.13.0):
Use `scala.jdk.CollectionConverters` instead
res4: scala.collection.mutable.Buffer[Integer] = Buffer(2, 3, 5, 7, 11, 13, 17, 19, ...
scala> res4.toList
res5: List[Integer] = List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
scala> res5.scanLeft(0)(_ + _)
res7: List[Int] = List(0, 2, 5, 10, 17, 28, 41, 58, 77, 100, 129, 160, 197, ...
scala> res5.scanLeft(0L)(_ + _)
res12: List[Long] = List(0, 2, 5, 10, 17, 28, 41, 58, 77, 100, 129, 160, 197, ...
scala> res7.takeRight(1)
res15: List[Int] = List(1179908154)
scala> res12.takeRight(1)
res16: List[Long] = List(142913828922)所以是的,试着用long把素数加起来。
https://stackoverflow.com/questions/64020313
复制相似问题