问题
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