Odd results when calculating factorial

Asked

Viewed 100 times

0

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

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));
    }

}
  • It’s not the same because I want to know what the mistake in the way I did.

  • Not exceeding the maximum value of int? Replaced by float for you to see.

  • It worked! But instead of printar 62272... printou 6.2272..., has problem happen that?

1 answer

2

This happens because the type value 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 already impossible to represent the value with a variable int. You can fix 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 the type double is 1.7976931348623157E308 and, if I did the right tests, it is possible to calculate the factor up to 171.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.