You can write a recursive function, which I've illustrated below:
Note, however, that I'm using the largest positive integer data type
(Uint64), and that you can only get values for numbers up to 21 with it.
Anything larger throws an overflow exception, as the result is larger than
UInt64.MaxValue.
To calculate larger numbers, you would need to create your own integral data
type, with storage larger than 64 bits.
/// <summary>
/// Returns the factorial of any UInt64 less than 22
/// </summary>
/// <param name="n">The number to get a factorial for.</param>
/// <returns>The factorial of n.</returns>
/// <remarks>Throws an exception if the number passed is greater than
21</remarks>
public static UInt64 Factorial(UInt64 n)
{
UInt64 i = Factorial(n - 1, 0);
return i;
}
/// <summary>
/// Returns the factorial of any UInt64 less than 22
/// </summary>
/// <param name="n">The number to get a factorial for.</param>
/// <param name="ct">The count of iterations</param>
/// <returns>The factorial of n.</returns>
/// <remarks>Throws an exception if the number passed is greater than
21</remarks>
private static UInt64 Factorial(UInt64 n, int ct)
{
if (n == 0) return 1;
if (n < 0) throw new Exception("Factorials may not be determined for
negative numbers");
if (ct > 21) throw new Exception("Too many recursion levels");
return n * Factorial(n - 1, ct + 1);
}
--
HTH,
Kevin Spencer
Microsoft MVP
Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net