Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger or not BigInteger?

In Java, most of the primitive types are signed (one bit is used to represent the +/-), and therefore when I exceed the limits of the type, I can get unexpected results, like negative numbers.

Is there any better solution than using BigInteger for this, since BigInteger has performance issues and you need to use the class methods for basic arithmetic instead of the language operators (ruins readability)?

like image 366
Alon Gubkin Avatar asked May 05 '10 20:05

Alon Gubkin


People also ask

What is BigInteger used for?

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.

What is the difference between long and BigInteger?

BigInteger is capable of holding far bigger numbers than Long. BigInteger seems capable of holding (2 ^ 32) ^ Integer. MAX_VALUE, though that depends on the implementation (and, even if truly unbounded in the implementation, there will eventually be a physical resource limit) See explanation here.

What is the difference between BigInteger and integer?

The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.


2 Answers

No, there is not a better solution. If you are working with values that cannot fit into a long or a double then you will need to use a reference type like BigInteger, and Java does not support operator overloading.

Technically, I suppose you could have some mapping between signed and unsigned values, but if your goal is clean and simple code then this is not at all the way to go.

like image 154
danben Avatar answered Sep 30 '22 17:09

danben


Scala is really the solution here. In that language "operators" are really just in-fixed methods, and can be defined for arbitrary classes. In fact in your case they already are in the standard library. So you can have the power of special number representations but the clean syntax of Java primitive types.

Scala is battle-hardened and will be fully interoperable with your Java code.

like image 45
Yuvi Masory Avatar answered Sep 30 '22 18:09

Yuvi Masory