public static double DoFactorial(long n)
{
// hardcode the simplest
// 0! = 1
// 1! = 1
// 2! = 2
if (n == 0)
{
return 1;
}
else if (n == 1)
{
return 1;
}
else if (n == 2)
{
return 2;
}
// n! = 1 * 2 * 3 * ... * n
double nFactorial = 1;
for (int i = 2; i <= n; i++)
{
nFactorial = nFactorial * i;
}
return nFactorial;
}
How it works:
for n=5
nFactorial = 1, n=5
i = 1 => nFactorial = 1 * 1 = 1
i = 2 => nFactorial = 1 * 2 = 2
i = 3 => nFactorial = 2 * 3 = 6
i = 4 => nFactorial = 6 * 4 = 24
i = 5 => nFactorial = 24 * 5 = 120
which is the expected result