Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Calculate the Factorial of an Integer in C#

4.27/5 (4 votes)
18 Oct 2011CPOL 15.9K  
The System.Numeric.BigInteger class allows for calculating VERY LARGE values.I created a sample window form app to calculate the factorial of an input valueprivate void button1_Click(object sender, EventArgs e){ int inputValue; if (int.TryParse(this.textBox1.Text, out inputValue)...
The System.Numeric.BigInteger class allows for calculating VERY LARGE values.
I created a sample window form app to calculate the factorial of an input value
C#
private void button1_Click(object sender, EventArgs e)
{
    int inputValue;
    if (int.TryParse(this.textBox1.Text, out inputValue) && inputValue > 0)
    {
        BigInteger bigInt = 1;
        while (inputValue > 1)
        {
            bigInt = BigInteger.Multiply(inputValue--, bigInt);
        }
        label1.Text = bigInt.ToString();
        label2.Text = bigInt.ToString().Length + " Digits";

    }
    else
    {
        label1.Text = "Invalid Input";
        label2.Text = "";
    }
}


just so you know, 1000! has 2568 digits :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)