Sunday, October 13, 2013

Calculate Factorial

In C# there is, surprisingly in my opinion, no built in function to calculate the factorial of a number. The factorial is written as n! and is calculated by n * (n - 1) * ... * 2 * 1. For example is 5! = 5 * 4 * 3 * 2 *1 = 120.
Although the implementation is not hard in C#, I still want today to post a function, which calculates the factorial of a number and which then can be included via copy & paste to the own application. I hope to save the one or another some seconds or minutes with that.
The function Factorial() works iteratively, in every step it multiplies the current result with the counting variable. I chose unsigned int as data type to get the biggest possible range of values for positive integers.

        public ulong Factorial(ulong n)
        {
            ulong Result = 1;
            for (ulong i = 1; i <= n; i++)
            {
                Result *= i;
            }
            return Result;
        }

No comments:

Post a Comment