BigInteger addition is always 0
I have the following problem, when I try to add to the BigIntegers sum, the result remains 0.
Here is the code:
public void NumberOfOutcomes(int x, int y){
BigInteger first = BigInteger.valueOf(0);
BigInteger second = BigInteger.valueOf(0);
for(int i = 0; i <= (x / 2); i++){
first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) );
System.out.println("First " + first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) ));
}
for(int i = 0; i <= (y / 2); i++){
second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) );
System.out.println("Second " + second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) ));
}
System.out.println("First " + first);
System.out.println("Second " + second);
System.out.println(first.multiply(second));
}
Here fac
is the factorial function.
This is what happens on the terminal:
points1.NumberOfOutcomes (2, 3)
First 1
First 1
Second 1
Second 2
First 0
Second 0
0
+3
source to share
2 answers
The add
class method BigInteger
returns the sum of the operand and the value already stored in the object itself. But it doesn't store the result in the object (first or second). It doesn't work the same way as
first += value;
in fact, you should do it like this:
first = first.add(value);
+1
source to share