1

I've been working with some very big numbers lately, and it has gone to the extent where even my longs overflow. Is there any variable that never overflows?

1
  • BigInteger will solve your problem. Commented Oct 4, 2016 at 22:45

2 Answers 2

2

BigInteger solves the problem here.

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). 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. (Source)

You can create BigInteger like so:

BigInteger int1 = new BigInteger("2");
BigInteger int2 = BigInteger.valueOf(4);

// However, because Java has no operator overloading, you have to do this.
// int3 would be 6.
BigInteger int3 = int1.add(int2);
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe you should use BigInteger, but is is a class type, not a variable.

BigInteger bi = BigInteger.valueOf(num);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.