Why does my recursive factorial method always return 0? [duplicate]

烈酒焚心 提交于 2020-01-15 03:11:33

问题


I have created a recursive method to calculate the facortial of a number, however, it is always returning 0, and I can not see why. I have provided my code below:

public class projectTwenty {
    public static void main(String [] args) {
        int factorialAns = factorial(100);
        System.out.println(factorialAns);
    }
    private static int factorial(int n) {
        if (n == 0) {
          return 1;
        }else {
          return (n * factorial(n-1));
        }
    }
}

I have tried changing the way in which the function is called and how values are returned, no luck so far. I have also searched Google/StackOverflow for similar methods/questions and am yet to find a solution.


回答1:


Because 100 factorial has so much digits that it causes an overflow on the integer type. You can try it on a smaller values and it will work much better.

In case you want to actually calculate big factorials you can use the BigInteger class in java.




回答2:


factorial(100) is probably too large to fit in an int and you get an overflow. For smaller values of n it works fine.

12 is the highest int for which factorial(12) won't overflow.



来源:https://stackoverflow.com/questions/28582551/why-does-my-recursive-factorial-method-always-return-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!