Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger addition always 0

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

like image 824
Dimitar Avatar asked May 07 '15 09:05

Dimitar


1 Answers

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(...).

like image 142
Tedil Avatar answered Sep 29 '22 12:09

Tedil