user435421
user435421

Reputation: 927

Java ArithmeticException BigInteger would overflow supported range

I am working on a algorithm to check if number is prime and need to work with really big numbers therefore I am using BigInteger class. Problem is that this exception is thrown ArithmeticException BigInteger would overflow supported range.

Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range
    at java.math.BigInteger.reportOverflow(Unknown Source)
    at java.math.BigInteger.checkRange(Unknown Source)
    at java.math.BigInteger.<init>(Unknown Source)
    at java.math.BigInteger.shiftLeft(Unknown Source)
    at java.math.BigInteger.pow(Unknown Source)
    at Kitas.main(Kitas.java:118)

And the line where exception is thrown:

b = BigInteger.valueOf(2).pow((int) (35*(Math.pow(2, counter))));

Once counter reaches value of 26, an exception is thrown.

Upvotes: 3

Views: 4270

Answers (2)

Davis Broda
Davis Broda

Reputation: 4125

BigInteger uses an int[] in order to store the value of the array. This means that the number cannot be larger than 2^(Integer.Max_Value), as anything larger than that would make the index of the array (stored in a single int) to be larger than the maximum size of the array.

at 26, the number you are storing is:

2^(35*[2^26]) = 2^2348810240 

the power of two used here (2,348,810,240) is slightly larger than (2^31-1), which is the maximum value that can be stored in a BigInteger due to the implementation of the BigInteger's internal storage. Going above a counter of 26 only makes this problem worse.

If you really need to work with numbers this large you may have to write your own version of BigInteger, which uses something else to store its values, which allows more storage space. Maybe a 2-D array like so: int[][] storage, as that could hold values up to 2^(2^(2^32-1)-1). If you need more than that, you can keep increasing the array's dimensions until you run out of memory on your computer - if completely filling an int[][] won't already do that (I suspect it will).

See documentation for more info.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198014

(int) (35 * Math.pow(2, 26)) == (int) (2348810240d) = Integer.MAX_VALUE

with the result that the power you're trying to raise 2 to is Integer.MAX_VALUE, so the result would have over Integer.MAX_VALUE binary digits. BigInteger isn't big enough for that, and storing numbers that large is pretty impractical.

Nothing built into Java will let you test primality of numbers that large.

Upvotes: 5

Related Questions