开发者

Problems with java.math.BigInteger

I have the following code at the head of a method:

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

This is supposed to load a min to a value (1 * 2 * 3 * ... * 199 * 200), and then set triNum to the first *triangle number** with a value greater than min.

Problem is, when I run the method, all I get is a terminal window with a list of "triNum: 0" ever scrolling down the screen... I don't see anything in my code (although it is completely possible I made some mistake, and I am somewhat unfamiliar with math.BigInteger), and this seems to point back to the BigInteger class. Anyone see a bug in my code?

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

*A triangle number is a number that 开发者_Python百科can be reached by: 1+2+3+4+5+6+7+...


Look at

foo.add(BigInteger.ONE);

Does this update foo? Or does it create an object that's equal to foo+ BigInteger.ONE which is not used again?


foo is always 0. You need to change this line:

foo.add(BigInteger.ONE);

to this:

foo = foo.add(BigInteger.ONE);


 foo.add(BigInteger.ONE);

As BigIntegers are immutable, you need to assign the result to foo again:

 foo = foo.add(BigInteger.ONE);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜