2

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.

  • You ought to know that this is not a good way to calculate factorials. You'd be better off with doubles, lngamma function, and memoization. – duffymo Feb 18 '15 at 12:46

2 Answers2

4

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.

Christo S. Christov
  • 2,268
  • 3
  • 32
  • 57
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.

Eran
  • 387,369
  • 54
  • 702
  • 768