Search code examples
javafactorial

Output of Factorial program


I am writing a program that should output the factorial of any number which is inputted by the user. The program correctly gives an output from 0 to 12 but if I enter 13, the output is 1932053504 but in my calculator, 13! = 6227020800.

Also in 32! and 33!, the output is negative (32! = -2147483648). Starting 34!, the output is zero(0).

How can I fix this? I want the program to provide the correct output of any number entered by the user.

import java.util.Scanner;
import java.io.*;
    public class one {

        public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int val = in.nextInt();
        int factorial = 1;

        for (int i = 1; i <= val; i++) {
            factorial *= i;
        }
        System.out.println("The factorial of " + val + " is " + factorial);
   }
}

Solution

  • It exceeds the max value an integer can take

    Max integer value:2147483647

    Max long value: 9223372036854775807

    Max double value: 7976931348623157^308

    Use long, double or BigInteger, which doesn't have upper boundaries

     public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.print("Enter number: ");
            int val = in.nextInt();
            int factorial = 1;
            int i = 1;
            while (i <= val) {
                factorial = factorial * i;
                i++;
            }
            System.out.println("The factorial of " + val + " is " + factorial);
        }
    }
    

    That's how you'd do it with a while loop instead