2

I was multiplying very two huge BigIntegervalues in a program. It failed. What are the limits of BigInteger and BigDecimal ?

Daanish
  • 1,061
  • 7
  • 18
  • 29
  • 2
    Are you sure the `NumberFormatException` occurs during multiplication? Can you show your code? The problem might be elsewhere. – mthmulders Jul 30 '13 at 11:38
  • 1
    `multiply` does not throw `NumberFormatException`. Show your code... – assylias Jul 30 '13 at 11:38
  • We really should instantly delete questions where someone reports an exception without posting the stacktrace. However, it's still better than just "it failed.". – Ingo Jul 30 '13 at 11:48

2 Answers2

6

You won't get NumberFormatException multiplying large numbers. If the number produced is too large, you will get a cryptic NegativeArraySizeException as the size of the array overflows.

You are more likely to get an out of memory error.

The limit is 32 * 2^32-1 bits for BigInteger or about 2^(4 billion).

You can get a NumberFormatException if you

  • create a BigInteger from an empty byte[]
  • use a signum < -1 or > +1
  • try to parse a number in base >36 or < 2
  • have a string with illegal digits.

When you get an exception you should also look at the message and the stack trace as this usually gives you the real cause.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Does that mean you actually can have "negative" array indexes? Otherwise, it would be 2^31-1 – Ingo Jul 30 '13 at 12:24
1

there shouldn't be a limit, except for memory, but maybe there is, according to the implementation of the class (for example, some fields there might be int or long).

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • 2
    As Peter pointed out, the limit is an indirect one, that results from the type for array indexing: Int. Because Big... is backed by int[], you cannot have an index like 8888888888888888888888888888888888. (But you'll likely get OutOfMemory before). – Ingo Jul 30 '13 at 11:51
  • is it because the max number of items for the array, which is the RAM memory (ok divided by 4, which is the size of int) ? wonder how much RAM is needed to hold this amount. – android developer Jul 30 '13 at 11:57
  • 1
    On a machine with 64bit address space, you could have an int array of size 2^62. (and nothing else) But long before this limit, Java kicks in, because you can't use long to index an array. – Ingo Jul 30 '13 at 12:05
  • so the implementation limit is what peter has written (and he decreased it by 1 because of negative numbers) ? – android developer Jul 30 '13 at 12:20