66

I understand that both java.lang.Long and java.math.BigIntegercan hold very large natural numbers.

I also know Long's max value, but what is the max value for BigInteger?

And aside from capacity, would BigInteger ever perform better when working with generally large integers that still fall in Long's range?

Question

Is the only consideration: is my value too large for Long?

Kelly S. French
  • 12,198
  • 10
  • 63
  • 93
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
  • 3
    BigInteger is capable of holding far bigger numbers than Long. http://stackoverflow.com/questions/12693273/is-there-an-upper-bound-to-biginteger – AHungerArtist Jul 31 '15 at 13:59
  • 8
    If Long is enough, use Long. If not, use BigInteger. – m0skit0 Jul 31 '15 at 14:00
  • Same way you choose between any numeric types. Is it possible for the value in question to exceed the size of a particular type? If so, use a larger type. – David Jul 31 '15 at 14:02
  • @Samha awesome rewrite - thank you! – Fritz Duchardt Nov 09 '15 at 08:25
  • 2
    @David I wouldn't say it's the case with "any numeric type". Take `Double` and `BigDecimal`. You would use `BigDecimal` if precision was critical, even though value range of `Double` is enough. – Saraph Oct 10 '16 at 08:12

1 Answers1

69

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.

The range of Long is [-9,223,372,036,854,775,808, +9,223,372,036,854,775,807].

Long will perform better than BigInteger so it really depends on what the size of your values will be. If they would all fall under Long's max value, it makes no sense not to use Long. If any would be bigger than the Long max value, you pretty much have to use BigInteger.

Community
  • 1
  • 1
AHungerArtist
  • 9,332
  • 17
  • 73
  • 109
  • 7
    Note that `(2 ^ 32) ^ Integer.MAX_VALUE` is implementation-dependent. Theoretically BigInteger has no max value. – m0skit0 Jul 31 '15 at 14:02
  • 1
    So, this is the only consideration then: is my value too large for Long? – Fritz Duchardt Jul 31 '15 at 14:14
  • 2
    @FritzDuchardt As far as I can see, yes. Long will definitely be better performing than BigInteger so size of your values is really the determining factor. – AHungerArtist Jul 31 '15 at 19:50