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

时间:2017-03-18 13:00:53

标签: java biginteger

我有以下代码

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相同

1 个答案:

答案 0 :(得分:4)

.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);
}