java.math.BigInteger的问题

时间:2009-10-20 01:45:11

标签: java biginteger

我在方法的头部有以下代码:

BigInteger foo = BigInteger.valueOf(0);
BigInteger triNum = BigInteger.valueOf(0);

//set min value to 1*2*3*4*5*...*199*200.
BigInteger min = BigInteger.ONE;
BigInteger temp = BigInteger.ZERO;
for(int i=1; i<=200; i++)
{
    temp = BigInteger.valueOf(i);
    min = min.multiply(temp);
}
System.out.println(min);

while(triNum.compareTo(min) <= 0)
{
    foo.add(BigInteger.ONE);
    triNum = triNum.add(foo);
    System.out.println("triNum: "+triNum);
}

这应该将min加载到一个值(1 * 2 * 3 * ... * 199 * 200),然后将triNum设置为第一个*三角形数**,其值大于min。

问题是,当我运行该方法时,我得到的是一个终端窗口,其中“triNum:0”列表在屏幕上向下滚动...我的代码中没有看到任何内容(尽管它完全是可能我犯了一些错误,我对math.BigInteger有点不熟悉,这似乎又指向了BigInteger类。有人在我的代码中看到了错误吗?

............................................... .................................................. .........................

*三角形数字是一个可以达到的数字:1 + 2 + 3 + 4 + 5 + 6 + 7 + ......

3 个答案:

答案 0 :(得分:9)

看看

foo.add(BigInteger.ONE);

这会更新foo吗?或者它是否创建了一个等于foo+ BigInteger.ONE但不再使用的对象?

答案 1 :(得分:4)

foo始终为0.您需要更改此行:

foo.add(BigInteger.ONE);

到此:

foo = foo.add(BigInteger.ONE);

答案 2 :(得分:3)

 foo.add(BigInteger.ONE);

由于BigIntegers是不可变的,您需要再次将结果分配给foo:

 foo = foo.add(BigInteger.ONE);