BigInteger的问题

Jos*_*itz 1 java biginteger

出于某种原因,BigInteger没有像我想的那样工作.我正在做BigVariable.add(BigVariable),但它不会添加.它的结果始终是它初始化的值.谁知道我错过了什么?提前致谢

代码用于项目euler 48

import java.math.BigInteger;


public class tuna {
public static void main(String[] args) {
    BigInteger result = BigInteger.ZERO;
    for(int i= 1; i <= 1000; i++)
        result.add( bigPow(BigInteger.valueOf(i), i) );
    System.out.println(result);
}
public static BigInteger bigPow(BigInteger number, int pow){
    if(pow < 1)
        throw new RuntimeException("bigPow can't handle exponents lower than 1");
    if (pow == 1)
        return number;
    return number.multiply( bigPow(number, pow-1) );
}

}
Run Code Online (Sandbox Code Playgroud)

dre*_*ash 6

尝试:

result = result.add( bigPow(BigInteger.valueOf(i), i) );
Run Code Online (Sandbox Code Playgroud)

代替:

result.add( bigPow(BigInteger.valueOf(i), i) );
Run Code Online (Sandbox Code Playgroud)

你需要这样做,因为BigInteger是不可变的(不可变的任意精度整数).所以你需要重新分配结果.

public BigInteger add(BigInteger val)

返回一个BigInteger,其值为(this + val).参数:val - 要添加到此BigInteger的值.返回:this + val