1

I am trying to add some large numbers to the initiated BigInteger but I am getting my output as 0 for any type of input, please help me for the same.

import java.util.Scanner;
import java.math.BigInteger;

public class NEO01 {

    public static void main(String []args){

        Scanner in = new Scanner(System.in);

        try{
            int t = in.nextInt();

            for(int i=0; i<t; i++){

                int n = in.nextInt();

                long[] a = new long[n];
                long count = 0;

                BigInteger sum_non_neg = new BigInteger("0");
                BigInteger sum_neg = new BigInteger("0");

                BigInteger s;

                for(int j=0; j<n; j++){

                    a[j] = in.nextInt();

                    if(a[j]<0){
                        s = BigInteger.valueOf(a[j]);
                        sum_neg.add(s);
                    }
                    else{
                        s = BigInteger.valueOf(a[j]);
                        sum_non_neg.add(s);
                        count++;
                    }   
                }

                s = BigInteger.valueOf(count);
                sum_non_neg.multiply(s);

                sum_non_neg.add(sum_neg);

                System.out.println(sum_non_neg);
            }
        }
        finally{
            in.close();
        }
    }
}
rjdkolb
  • 10,377
  • 11
  • 69
  • 89

1 Answers1

3

BigInteger is immutable, so calling add() on a BigInteger instance doesn't change its value, it returns a new BigInteger instance.

Since you ignore the returned value, your sum_neg and sum_non_neg remain unchanged.

You should assign the result of the addition back to your variables:

            if(a[j]<0){
                s = BigInteger.valueOf(a[j]);
                sum_neg = sum_neg.add(s);
            }
            else{
                s = BigInteger.valueOf(a[j]);
                sum_non_neg = sum_non_neg.add(s);
                count++;
            }   
Eran
  • 387,369
  • 54
  • 702
  • 768