BigInteger.pow() 直到最后 2 次迭代才起作用?

BigInteger.pow() doesn't work until last 2 iterations?

我有以下代码

public static void main(String[] args) {
    BigInteger iter = BigInteger.valueOf(140);
    BigInteger y = BigInteger.valueOf(1114112);
    BigInteger sum = BigInteger.valueOf(0);
    while(iter.intValue() != 0) {
        BigInteger z = BigInteger.valueOf((y.pow(iter.intValue())).longValue());
        sum = sum.add(z);
        iter = iter.subtract(BigInteger.valueOf(1));
        System.out.println("Itereration: " + (140 - iter.longValue()));
        System.out.println("Y: " + y.longValue());
        System.out.println("Z: " + z.longValue());
        System.out.println("Sum: " + sum.longValue());
   }
}

但是,输出是这样的(只有最后 3 次迭代)

Iteration: 137
Y: 1114112
Z: 0
Sum: 0
Iteration: 138
Y: 1114112
Z: 1382886560579452928
Sum: 1382886560579452928
Iteration: 139
Y: 1114112
Z: 1241245548544
Sum: 1382887801825001472
Iteration: 140
Y: 1114112
Z: 1114112
Sum: 1382887801826115584

迭代1-136的其余部分与迭代137相同

.longValue() 调用对这么大的 BigInteger 值做了完全错误的事情。如果您尝试改用 .longValueExact(),您会看到它抛出异常,因为值超出了 long 的范围。但是,如果您不执行不必要的 .longValue() 调用,则代码有效:

BigInteger iter = BigInteger.valueOf(140);
BigInteger y = BigInteger.valueOf(1114112);
BigInteger sum = BigInteger.valueOf(0);
while(iter.intValue() != 0) {
    BigInteger z = y.pow(iter.intValue();
    sum = sum.add(z);
    iter = iter.subtract(BigInteger.valueOf(1));
    System.out.println("Itereration: " + (140 - iter.longValue()));
    System.out.println("Y: " + y);
    System.out.println("Z: " + z);
    System.out.println("Sum: " + sum);
}

作为@RC。在评论中建议,您可以将 iter 设为简单的 int,从而进一步简化代码:

int iter = 140;
BigInteger y = BigInteger.valueOf(1114112);
BigInteger sum = BigInteger.valueOf(0);
while(iter != 0) {
    BigInteger z = y.pow(iter);
    sum = sum.add(z);
    iter--;
    System.out.println("Itereration: " + (140 - iter));
    System.out.println("Y: " + y);
    System.out.println("Z: " + z);
    System.out.println("Sum: " + sum);
}