0

I've got an array of BigIntegers, and I want to add them all into one BigInteger. I've used the method.add(), but for some reason, sum always remains 0.

BigInteger[] numbers = {
                new BigInteger("20849603980134001723930671666823555245252804609722"),
                .
                .
                .
                new BigInteger("53503534226472524250874054075591789781264330331690")
        };


BigInteger sum = new BigInteger("0");

        for(int i = 0; i < numbers.length; i++) {
            sum.add(numbers[i]);
            System.out.println(numbers[i]);
            System.out.println(sum);
        }
        System.out.println(sum);

Thank you for your help!

  • 1
    `sum = sum.add(numbers[i]);` – ArcticLord Oct 26 '16 at 11:17
  • `BigInteger` is immutable so it needs to be `sum = sum.add(numbers[i]);` - On a side note: `for(BigInteger number : numbers ) { sum = sum.add(number); }` would work as well. – Thomas Oct 26 '16 at 11:17

1 Answers1

3

BigInteger is immutable - calling sum.add(...) does nothing to sum but returns a new BigInteger.

So you need to change your code to:

sum = sum.add(numbers[i]);
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Oh my gosh! How did I not see that. So silly... thank you – Karen Sarmiento Oct 26 '16 at 11:19
  • 1
    @KarenSarmiento The point there is: you probably didn't see that because you didn't spend too much time reading the BigInteger Javadoc, did you? Thats the thing: when you start using some new thing you haven't used before ... it can save you a lot of them to first study that new thing. – GhostCat Oct 26 '16 at 11:24
  • Now, thats cool. First answer the question, and *then* close it as DUP. I am not exactly sure if the *community* would consider this to be the best order ... – GhostCat Oct 26 '16 at 11:25
  • @GhostCat I found the duplicate after answering - happy to delete this answer (I did after your comment) but not sure if it's the best course of action. See: http://meta.stackoverflow.com/questions/265957/closing-a-question-as-a-duplicate-then-answering-it – assylias Oct 26 '16 at 11:33
  • Your choice. I am just jealous because you were quicker writing up that answer; and then when I thought "maybe a dup anyway" you were quicker ... again. – GhostCat Oct 26 '16 at 11:36