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>Thro ws an exception if the number passed is greater than
21</remarks>
public static UInt64 Factorial(UInt6 4 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>Thro ws an exception if the number passed is greater than
21</remarks>
private static UInt64 Factorial(UInt6 4 n, int ct)
{
if (n == 0) return 1;
if (n < 0) throw new Exception("Fact orials 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
"Sugandh Jain" <su**********@n irvana-sol.comwrote in message
news:eq******** ******@TK2MSFTN GP02.phx.gbl...
Hi.
How to write a function that will return me the factorial (say in a
string) for the any positive integer it takes?
When we find a factorial of even say 2000 or a higher number, it will be
very big to be accomodated in int or long datatype.
Regards,
Sugandh