65.9K
CodeProject is changing. Read more.
Home

Calculate the Factorial of an Integer in C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (5 votes)

Oct 3, 2011

CPOL
viewsIcon

93901

I looked for a while over the net for a way to easily calculate a factorial value (n!), but nothing was helping and I saw some VERY long and drawn out solutions. Well, it wasn't that hard after I thought about it for a while and this was the easiest solution I could come up with. I hope it helps! The code below is what I put in my event handler. The comment lists my class variables used.
int Factorial(int input)
{
    int answer = 0;

    if (input > 0)
    {
        count = 1;
        while (count <= input)
        {
            if (count == 1)
            {
                answer= 1;
                count++;
            }
            else
            {
                answer = count * answer;
                count++;
            }
        }
    }
    else
    {
        MessageBox.Show("Please enter only a positive integer.");
    }

    return answer;
}