Strange results when calculating factorial [duplicate]

0

I can not seem to find the error in my code. When I put numbers smaller or equal to 12 my program gives the right result, but from number 13 the values go out wrong and I can not know why. What is wrong?

class vdois {

    static int fatorial (int numero){
        int fat = 1;
        while (numero >0) {

            fat *= numero;
            numero--;
        }

        return fat;
    }


    public static void main(String[] args) {
        int numero = 13;
        System.out.println(numero+"! = "+fatorial(numero));
    }

}
    
asked by anonymous 06.05.2017 / 20:42

1 answer

1

This happens because the value of type int is at most 2,147,483,647. If you calculate the factorial of 13, you will see that it is worth 6,227,020,800, that is, it is no longer possible to represent the value with a int variable. You can correct this by changing the type to double :

class vdois {

    static double fatorial (int numero){
        double fat = 1;
        while (numero >0) {

            fat *= numero;
            numero--;
        }

        return fat;
    }

    public static void main(String[] args) {
        int numero = 13;
        System.out.println(numero+"! = "+fatorial(numero));
    }

}

With this, you already increase the range of possible values in the input, because the maximum value of type double is 1.7976931348623157E308 and, if I did the right tests, it is possible to calculate the factorial of up to 171.     

06.05.2017 / 21:09