繁体   English   中英

Java BigInteger 返回不正确的值

[英]Java BigInteger Returning Incorrect Value

我正在尝试使用 BigInteger 生成 n 位数。

for(int i=0;i<n;i++){
    genL = genL.add(BigDecimal.valueOf(Math.pow(10,i)).toBigInteger());
    System.out.println(i + " "+ genL);
            }

我期待 output 结果序列中的所有人。 但我得到了下面的 output。 i = 23 和 24 插入零。有什么我遗漏的吗?

0 1

1 11

2 111

3 1111

4 11111

5 111111

6 1111111

7 11111111

8 111111111

9 1111111111

10 11111111111

11 111111111111

12 1111111111111

13 11111111111111

14 111111111111111

15 1111111111111111

16 11111111111111111

17 111111111111111111

18 1111111111111111111

19 11111111111111111111

20 111111111111111111111

21 1111111111111111111111

22 11111111111111111111111

23 111111111111111101111111

24 1111111111111111101111111

有什么我错过的吗?

是的。 Math.pow(10,i)返回一个double并且只有 53 位精度。


您可以改写代码以使用BigInteger.pow方法。

但是,(IMO)更简单的版本将是

genL = BigInteger.ZERO;
for (int i = 0; i < n; i++) {
    genL = genL.mult(BigInteger.TEN) + BigInteger.ONE;
    System.out.println(i + " " + genL);
}

或者,如果您只关心output 的外观,只需使用字符串生成器/字符串连接; 例如

genL = new StringBuilder();
for (int i = 0; i < n; i++) {
    genL.append("1");
    System.out.println(i + " " + genL);
}

使用BigInteger(String val)构造函数创建BigInteger会更简单(也更有效):

new BigInteger("111111111111111111111111111111"); // as many 1s as you want

或者,概括地说:

char[] ones = new char[n];
Arrays.fill(ones,'1');
BigInteger genL = new BigInteger(new String (ones));

Math.pow返回一个双精度值,这不能保证大数字的精确度。

在这种情况下, Math.pow(10, 23)返回1.0000000000000001E23 ,当转换为 BigInteger 时,它变为100000000000000010000000 ,从而导致中间的0

我建议您将Math.pow(10, i)替换为BigInteger.TEN.pow(i)

您应该按如下方式使用我的代码,就像一个魅力!

    BigInteger i = new BigInteger("0");
    BigInteger ten = new BigInteger("10");
    BigInteger one = new BigInteger("1");
    for (int j = 0; j < 64; j++) {
        i = i.multiply(ten).add(one);
        System.out.println(i);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM