为什么java.Math.BigInteger在一定限制后出错?

kBi*_*sla 1 java biginteger

我试图打印2 ^ n中的数字总和,n = 1到1000.这就是我所做的.

public static void main(String[] args) {
    int n = 1000;
    for (int i = 1; i < n; i++) {
        BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
        int sum = 0;
        while (power.intValue() > 0) {
            sum += power.intValue() % 10;
            power = power.divide(BigInteger.valueOf(10));
        }
        System.out.print(sum + "  ");
    }
}
Run Code Online (Sandbox Code Playgroud)

它只能工作到大约2 ^ 30左右,然后打印相同的结果,46,其余的.

我在C中使用"long long"尝试过类似的东西,并且在类似限制之后打印0.

根据答案,我改变了

BigInteger power = BigInteger.valueOf((int)Math.pow(2, i));
Run Code Online (Sandbox Code Playgroud)

BigInteger power = BigInteger.valueOf(2).pow(i);
Run Code Online (Sandbox Code Playgroud)

和46改为0.就像C.仍然没有工作......

Jes*_*mos 7

您正在使用Math.pow生成应该使用BigInteger函数的值来代替.

总和应存储在BigInteger中,而不是int.


ζ--*_*ζ-- 7

你正在进行整数运算,然后将它放入一个大整数.使用biginteger的pow方法代替.