Factorial java return 0

后端 未结 4 1508
轻奢々
轻奢々 2021-01-24 06:51

I made a simple function to calculate the factorial of a number but from number 34 returns 0 . It should be from number 51 .

   public class Métodos {
       pub         


        
4条回答
  •  醉话见心
    2021-01-24 07:28

    1- I'm a native Portuguese speaker and please follow my advice: "Write code in English." It is easier for the world to read and when you get to conventions your methods will have names like getSomething() or setSomething(something).

    2- About your problem. Try:

    for (int i = 0 ; i < 60; i++){
        System.out.println(i + " " + factorial(i));
    }
    

    You will see that around 12 you start getting strange values because an int in java is limited to 2^31-1 and you are getting overflows: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    You can try a long. But that will also overflow long before 51.

    You will have to use the BigInteger class that handles arbitrary values.

    public static BigInteger factorial(BigInteger number) {
        if ((number.compareTo(BigInteger.ZERO) == 0)
                || (number.compareTo(BigInteger.ONE) == 0)) {
            return BigInteger.ONE;
        } else {
            return number.multiply(factorial(number.subtract(BigInteger.ONE)));
        }
    }
    

提交回复
热议问题