Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigInteger alternative

Is there a way to improve BigInteger performance with caching?

When you operate on BigInteger it always creates a new BigInteger. For example, when you multiply two big integers, a new BigInteger is created to host the result. I want to use some mutable version of a BigInteger that will update one of the fields with the result.

like image 834
Ilya Gazman Avatar asked Jan 25 '16 15:01

Ilya Gazman


People also ask

What is bigger than BigInteger in Java?

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. It's size limit is the available memory.

Is BigInteger slow Java?

Add: BigInt is fastest due to its mutability. Apint is by far the slowest, since it uses a power of 10 base. Sub: The same goes here. Apint is slow when it comes to simple arithmetic operations.

Does Java have BigInt?

BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.


1 Answers

I doubt that the performance of your algorithm will improve if you could somehow do this, but the main principle is that BigInteger is immutable. You cannot perform an operation on it without generating a new instance, and there are good reasons to want this behavior - namely, if you have multiple threads operating on a single BigInteger, you can rest assured that these threads aren't overwriting that BigInteger directly*.

If you don't desire this behavior, your only option is to create a new class, but bear in mind that you will still be dealing with the immutability of BigIntegers at some layer.

*: Y'know, so long as you're not reassigning the variable...

like image 112
Makoto Avatar answered Sep 28 '22 08:09

Makoto