Java BigInteger返回错误的值



我正在尝试使用BigInteger生成n位数字和所有1。

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

我期待输出结果序列中的所有结果。但我得到了以下输出。对于i=23和24,将插入零。我遗漏了什么吗?

0 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 1111111111111111

20 111111111111111111111111

21 1111111111111111111111111

22 1111111111111111111

23 1111111111111111 01111111

24 11111111111111111 01111111

我遗漏了什么吗?

是的。CCD_ 1正在返回一个CCD_。


您可以重写代码以使用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);
}

或者,如果您只关心输出是什么样子,只需使用字符串生成器/字符串连接即可;例如

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

Math.pow返回一个双值,无法保证大数字的精确性。

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

我建议你用Math.pow(10,i)0代替Math.pow(10, i)

使用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));

您应该按照如下方式使用我的代码,工作起来很有魅力!

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

最新更新