views:

237

answers:

3

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 can be reached by: 1+2+3+4+5+6+7+...

+8  A: 

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?

S.Lott
Thanks a lot, that should have been obvious, lol. =)
Jonathan
+4  A: 

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

foo.add(BigInteger.ONE);

to this:

foo = foo.add(BigInteger.ONE);
tster
+3  A: 
 foo.add(BigInteger.ONE);

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

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