The Factorial Function is a classic interview question. It opens the doors to a discussion about stack overflow (if done recursively) and integer overflow (if the param is too large) as well as discussions around how to handle and catch errors.
Here is one way to do it using recursion:
static Int64 Factorial(int factor)
{
if (factor > 1)
{
return factor * Factorial(--factor);
}
return 1;
}
Here is another way to do it using a loop:
static Int64 Factorial(int factor)
{
Int64 factorial = 1;
for (int i = 1; i <= factor; i++)
{
factorial *= i;
}
return factorial;
}
Neither function does any sanity checks for input (e.g. >= 1) and assumes that we're looking for a factorial of 1 or greater.
There's a third and much better way to do factorials if you are going to use them in code that needs to be optimized. In fact I can't think of a reason why you wouldn't want to use the following method. If you are calculating an Int64 factorial then the maximum factor that you can calculate it for is 20. After that it will overflow the Int64 type. If you are calculating an Int32 factorial then the highest you can go is 12.
static Int64[] factors64 = { 0, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600, 6227020800, 87178291200,
1307674368000, 20922789888000, 355687428096000, 6402373705728000,
121645100408832000, 2432902008176640000 };
static Int64 Factorial(int factor)
{
return factors64[factor];
}
The tests that I ran showed the recursive factorial function to run 14 times slower than the array lookup and the loop to run 5 times slower.