Search code examples
javamathfactorial

Why does my recursive factorial method always return 0?


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.


Solution

  • 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.