Can Java optimize "mutating" BigInteger operations in loops?

java

Solution

Yes, there is a `java.math.MutableBigInteger` class that is used by `BigInteger` for compute-intensive operations. Unfortunately, it is declared as package private, so you cannot use it. There is also a "MutableBigInteger" class in the Apache Commons library, but it is just a mutable wrapper for BigInteger and that is no help for you.

I was wondering if Java can optimize this somehow ...

No ... not withstanding the above.

or whether I should just write my own BigInteger class.

That's one approach.

Another is to to download the OpenJDK sources, find the source code for `java.math.MutableBigInteger`, change its package name and access, and incorporate it into your code-base. The only snag is that OpenJDK is licensed under the GPL (GPL-2 I think), and that has implications if you ever distribute code using the modified class.

See also:

- What is the purpose of java.math.MutableBigInteger?

Problem

I need to deal with a lot of big numbers much larger than a long (>10^200), so I'm using BigIntegers. The most common operation I perform is adding them to an accumulator, ex: ``` BigInteger A = new BigInteger("0"); for(BigInteger n : nums) { A = A.add(n); } ``` Of course making copies for destructive actions is quite a waste (well, as long as there's a large enough buffer available), so I was wondering if Java can optimize this somehow (I heard there was a MutableBigInteger class not exposed by math.java) or whether I should just write my own BigInteger class.

Original source

Related problems