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.
The standard library BigInteger class in Java is known to be notoriously slow (at least for Java 7 and earlier, and I doubt Java 8 is any different).
Java For TestersBigInteger one = new BigInteger("98765432123456789"); BigInteger two = new BigInteger("94353687526754387"); BigInteger three = new BigInteger("96489687526737667"); Apply mathematical operations on them.
The largest primitive data type that can store integer values in Java is the 64-bit long. Given that it is a signed data type, this gives it the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Is there a variable type bigger than BigInteger? No there isn't. Biginteger uses byte arrays behind the scenes and just allocates more space for it whenever it needs it.
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:
A quicker solution is to circumvent the java package visibility. You can do that by creating a package named java.math in your own project and creating a public class that exposes the package private MutableBigInteger like so:
package java.math;
public class PublicMutableBigInteger extends MutableBigInteger {
}
Then you can just import java.math.PublicMutableBigInteger; and use it as any other class. This solution is quick and doesn't impose upon you any particular licence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With