如何使用 BigInteger? [英] How to use BigInteger?
本文介绍了如何使用 BigInteger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码,但它不起作用:
I have this piece of code, which is not working:
BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
if (isPrim(i)) {
sum.add(BigInteger.valueOf(i));
}
}
sum 变量始终为 0.我做错了什么?
The sum variable is always 0. What am I doing wrong?
推荐答案
BigInteger
是不可变的.javadocs 声明 add() "[r] 返回一个 BigInteger,其值为 (this + val)."因此,你不能改变sum
,你需要将add
方法的结果重新赋值给sum
变量.
BigInteger
is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum
, you need to reassign the result of the add
method to sum
variable.
sum = sum.add(BigInteger.valueOf(i));
这篇关于如何使用 BigInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文