Given my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Fact_2 {
public static void main(String args[]) throws IOException {
System.out.println("Please enter a number:");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int fact = Integer.parseInt(input.readLine());
int factorial = 1;
for (int i = 1; i <= fact; i++) {
factorial = factorial * i;
}
System.out.println("The factorial of " + fact + " is " + factorial);
}
}
The program works correctly...only up to the 12th digit. I checked to make sure all the factorials were right but when you enter 13 for your number you get 1932053504 when it should be 6227020800. Why is that?
I just want to add the mathematical reasoning with regards to the integer overflow:
12! = 479,001,600
13! = 6,227,020,800
Now, the range limit for int
(32-bit) type is:
-2,147,483,648 to 2,147,483,647
which is exceeded just when the factorial becomes 13 since:
479,001,600 < 2,147,483,647 < 6,227,020,800
Because of the overflow, when you have 13 factorial, it treats it as:
13! = 6,227,020,800 % 4,294,967,296
= 1,932,053,504 + 4,294,967,296 x 1 % 4,294,967,296
= 1,932,053,504
To fix it, use BigInteger
. If you don't need it to be too large, use long
which has capacity of:
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
long
can handle up to 20!
20! = 2,432,902,008,176,640,000
Beyond that, you need to use BigInteger