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

boolean correctInputn= false;
    
    while(!correctInputn)
    {
    long number;// declares variables for storing number
    long factorial = 1;// declare variable for storing factorial
    

    System.out.println("Enter a number between 1 and 25"); // tells user to enter number
    number = scanner.nextLong();
    
         if (number <0)  
            {System.out.println("Positive numbers only");// if number entered is negative
             correctInputn = false; continue;} // if user enters number less than 0 loops back to code start
       
       
         else if (number > 25)
             { System.out.println("Number to large to print");
               correctInputn = false; continue;} // if user enters number over 25 loops back to code start
        
    
          else  {
      // if user enter 10, counter starts at 10 and runs to two
        for(long mynumber = number; mynumber >= 1; mynumber--) {
            factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
        }
    
    System.out.println("The factorial of " + number +" is equal to " + factorial);
    break;
    }
    }

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