Skip to content
Advertisement

How do I prevent a long overflow?

My assignment ask us to ask the user to enter a number and print the factorial of it,

it also ask us to not allow the user to chose any negative number or number over 25, when they do, we loop them back to scanner to re renter a number

we were also told to store the number in a long, but when I do, if the user enters a number over 20 and =<25, the answer becomes a negative causing a long overflow.

I tried changing the long to BigInteger, but when I keep getting an error on ever line i use BigInteger instead of long

JavaScript

Advertisement

Answer

BigInteger is a reference type – like all types in java except the hardcoded list of long, int, double, short, float, char, byte, and boolean. You can invoke methods on it. The + can be used if the thing on its left’s type is a String which will invoke toString() on them and concatenate them. That’s it. They do not ‘support’ -, +, *, etcetera. Instead, they have the methods .multiply and .add and friends. Note that this doesn’t add a number to the object, it calculates the value and returns it, e.g. you’d write factorial = factorial.multiply(myNumber). You’ll have to replace all operators with the appropriate method, and you’ll have to turn all numbers in BigInteger objects, using BigInteger.valueOf(20) for example.

You can’t magically prevent longs from overflowing. It’s a fundamental aspect of math on 64-bit numbers: You can’t store more than 2^64 different things in 64-bits for the same reason 1+1=2 – because of fundamental mathematical reasons.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement