Tim
Tim

Reputation: 375

Dealing with extremely large numbers

So I have to deal with really large numbers. In fact, the exact number is 18,446,744,073,709,551,616 which is 2^64. I guess I could write it just as 2^64, but then I'm going to be subtracting numbers from it and dividing and whatever, and some of my calculations might also be in the quintillions. I tried adding "L" to the end of it like so:

public int total = 18446744073709551616L;

However, it is still giving me the same error as the integer being too large. I'm not sure if this is because I'm typing it in wrong or it is still too large even with the 'L'. Any solution around this? I'm definitely willing to expend a bit of processing power or adding extra runtime, as long as it works. Merci!

Upvotes: 1

Views: 505

Answers (2)

Artem
Artem

Reputation: 7423

I believe in your case only BigInteger or BigDecimal will be solution.

Upvotes: 0

You can use java.math.BigInteger.

Create the BigInteger from a string, using new BigInteger("18446744073709551616").

You can perform mathematical operations by calling methods, such as add, subtract, multiply, divide and mod. You cannot use the +, -, *, /, % operators as they only work on primitive types (and + on Strings).

Upvotes: 3

Related Questions