-1

I made code which computes the factorial of the user inputted number, but anything past 12! I get the wrong number and anything past 16! I get negative numbers. What is the reason for this and is there a solution fix this?

import java.util.Scanner;

class Factorial {
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        Integer input = keyboard.nextInt(); 

        int fact = 1;

        for (int i = 1; i <= input; i++) {
            fact = fact * i;
        }

        System.out.println(fact); 
        keyboard.close(); 

    }
}

Mark
  • 161
  • 7
  • 4
    anything > 12! overflows the integer value space; that's what you're seeing – Janus Varmarken Oct 05 '19 at 01:52
  • Also helpful: [Why does Java think that the product of all numbers from 10 to 99 is 0?](//stackoverflow.com/q/26375932) – Tom Oct 05 '19 at 01:57
  • To get around your issue, use a different data type, one that has a wider range. For instance: `long fact = 1L;` But know the limits! You might want to read about java data types: w3schools.com/java/java_data_types.asp – RoyM Oct 05 '19 at 02:01
  • Yes you're right, duplicate. I did not see that when i searched. Thank you – Mark Oct 05 '19 at 02:07

1 Answers1

1

4 bytes int limit is 2147483647. Factorial 13 is 6227020800. Factorial 13 value is overflowing the int range. Try using long for your case.