1

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+...

Jonathan
  • 541
  • 4
  • 9
  • 19
  • 4
    Apart from the error with foo.add, please notice that your program will take a very long time to run, so you should find another way to do what you want. As a hint, there's an easy formula to find out what the sum 1+2+3+4...+n is without having to add all the numbers. – schnaader Oct 20 '09 at 01:56
  • Very long as in much much longer than the life of the universe (the result has 188 digits). – starblue Oct 20 '09 at 06:15

3 Answers3

9

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
  • 384,516
  • 81
  • 508
  • 779
4

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

foo.add(BigInteger.ONE);

to this:

foo = foo.add(BigInteger.ONE);
tster
  • 17,883
  • 5
  • 53
  • 72
3
 foo.add(BigInteger.ONE);

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

 foo = foo.add(BigInteger.ONE);
Thilo
  • 257,207
  • 101
  • 511
  • 656