如何使用BigInteger?
我有这段代码,但是没有用:
BigInteger sum = BigInteger.valueOf(0); for(int i = 2; i < 5000; i++) { if (isPrim(i)) { sum.add(BigInteger.valueOf(i)); } }
sum变量总是0.我做错了什么?
BigInteger
是不可变的。 javadocs声明add() “[r] eturns一个BigInteger,其值为(this + val)。” 因此,您无法更改sum
,您需要将add
方法的结果重新分配给sum
变量。
sum = sum.add(BigInteger.valueOf(i));
sum = sum.add(BigInteger.valueOf(i))
BigInteger
类是不可变的,因此您无法更改其状态。 所以调用“add”会创建一个新的BigInteger
,而不是修改当前的。
其他答复已经钉了它; BigInteger是不可变的。 这是使代码工作的微小变化。
BigInteger sum = BigInteger.valueOf(0); for(int i = 2; i < 5000; i++) { if (isPrim(i)) { sum = sum.add(BigInteger.valueOf(i)); } }
java.math.BigInteger
是一个不可变类,因此我们无法在已分配对象的位置分配新对象。 但您可以创建新对象来分配新值,如:
sum = sum.add(BigInteger.valueOf(i));
BigInteger是一个不可变的类。 因此,无论何时进行任何算术运算,都必须将输出重新分配给变量。
是的,它是永恒的
sum.add(BigInteger.valueOf(i));
所以BigInteger类的方法add()不会将新的BigIntger值添加到它自己的值,但是创建并返回一个新的BigInteger引用而不更改当前的BigInteger, 即使在字符串的情况下也是如此
Biginteger
是一个不可变的类。 您需要将输出的值明确指定为总和,如下所示:
sum = sum.add(BigInteger.valueof(i));
其实你可以用,
BigInteger sum= new BigInteger("12345");
用于为BigInteger类创建对象。但问题是,你不能在双引号中给出一个变量。所以我们必须使用valueOf()方法,我们必须再次将答案存储在那个总和中。所以我们会写,
sum= sum.add(BigInteger.valueOf(i));
由于您总结了一些int值,因此无需使用BigInteger。 long
就足够了。 int
是32位,而long
是64位,可以包含所有int值的总和。