I got many answers for this when I Googled "How to find factorial of a number"...
One of those examples is...
private double getFactorial(double f){
if ( f == 0 )
return 1;
return (f * getFactorial(f - 1));
}
And it works... However, the Windows Calculator surprised me: It works for decimal numbers as well!!
For example: On the Windows Calculator, the factorial of 0.5
is 0.886226925
...
Is that the desired behavior? Is the factorial defined for non-integers?
Making my comment an answer:
The factorial can be generalized to nearly all numbers (real/complex/non-integral) via the Gamma Function.
The only points for which it is still undefined are for negative integers due to singularities. (This is easy to see by reversing the recursion identity for the factorial. Going from 0!
to (-1)!
leads to a divide by zero.)
Obviously, your code will work only for integers. For anything else it will go into an infinite recursion and cause a stackoverflow.
For integers, it's easy to compute it with a simple loop or a recursion. But for anything else, it's much harder to do.
There are two main algorithms for evaluating the factorial/Gamma Function at non-integral points:
Wikipedia has an implementation of the latter in Python.