Reputation: 4783
I have the following issue: when trying to add to a sum of BigIntegers the outcome 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.
Here is what comes on the terminal:
points1.NumberOfOutcomes(2, 3)
First 1
First 1
Second 1
Second 2
First 0
Second 0
0
Upvotes: 8
Views: 6305
Reputation: 597
The add
method of BigInteger
class returns the sum of the operand and the value already stored in the the object itself. But it does not store the result in the object (first or second).
It doesn't work in the same way as
first += value;
actually, you have to make it look like this:
first = first.add(value);
Upvotes: 1
Reputation: 1933
This is because BigInteger
is immutable which means that its value does not change. So first.add(x)
will create a new BigInteger
containing the computations result, i.e. just reassign the result to first, like first = first.add(...)
.
Upvotes: 22