首页 文章

如何使用BigInteger?

提问于
浏览
146

我有这段代码,但是没有用:

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
    if (isPrim(i)) {
        sum.add(BigInteger.valueOf(i));
    }
}

sum变量总是0.我做错了什么?

9 回答

  • 195

    BigInteger 是不可变的 . javadocs表示add() "[r]eturns a BigInteger whose value is (this + val)."因此,您无法更改 sum ,需要将 add 方法的结果重新分配给 sum 变量 .

    sum = sum.add(BigInteger.valueOf(i));
    
  • 11
    sum = sum.add(BigInteger.valueOf(i))
    

    BigInteger 类是不可变的,因此您无法更改其状态 . 所以调用"add"会创建一个新的 BigInteger ,而不是修改当前的 .

  • 1

    其他答复已经钉了它; BigInteger是不可变的 . 这是使代码工作的微小变化 .

    BigInteger sum = BigInteger.valueOf(0);
    for(int i = 2; i < 5000; i++) {
        if (isPrim(i)) {
            sum = sum.add(BigInteger.valueOf(i));
        }
    }
    
  • 20

    java.math.BigIntegerimmutable 类,因此我们无法在已分配对象的位置分配新对象 . 但是您可以创建新对象来分配新值,如:

    sum = sum.add(BigInteger.valueOf(i));
    
  • 56

    BigInteger是一个不可变的类 . 因此,无论何时进行任何算术运算,都必须将输出重新分配给变量 .

  • 10

    是的,它是永恒的

    sum.add(BigInteger.valueOf(i));
    

    所以bigInteger类的方法add()不会将新的BigIntger值添加到自己的值,但是 creates and returns a new BigInteger reference 而不更改当前的BigInteger和 this is what done even in the case of Strings

  • -6

    Biginteger 是一个不可变类 . 您需要将输出的值明确指定为总和,如下所示:

    sum = sum.add(BigInteger.valueof(i));
    
  • 0

    其实你可以用,

    BigInteger sum= new BigInteger("12345");
    

    用于为BigInteger类创建对象 . 但问题是,你不能在双引号中给出一个变量 . 所以我们必须使用 valueOf() 方法,我们必须再次将答案存储在那个总和中 . 所以我们会写,

    sum= sum.add(BigInteger.valueOf(i));
    
  • 3

    由于您总结了一些int值,因此无需使用BigInteger . long 就足够了 . int 是32位,而 long 是64位,可以包含所有int值的总和 .

相关问题