Click here to Skip to main content
15,883,990 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Calculate the Factorial of an Integer in C#

Rate me:
Please Sign up or sign in to vote.
4.27/5 (4 votes)
18 Oct 2011CPOL 15.5K   1
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)


Written By
Software Developer (Senior) CodeProject
Canada Canada
As Senior Architect, Matthew is responsible for the Architecture, Design, and Coding of the CodeProject software as well as Manager of the Infrastructure that runs the web site.

Matthew works on improving the performance and experience of the Code Project site for users, clients, and administrators.

Matthew has more years of software development, QA and architecture experience under his belt than he likes to admit. He graduated from the University of Waterloo with a B.Sc. in Electrical Engineering. He started out developing micro-processor based hardware and software including compilers and operating systems.
His current focus is on .NET web development including jQuery, Webforms, MVC, AJAX, and patterns and practices for creating better websites.
He is the author of the Munq IOC, the fastest ASP.NET focused IOC Container.
His non-programming passions include golf, pool, curling, reading and building stuff for the house.

Comments and Discussions

 
GeneralMatthew, have a look at this site: http://www.luschny.de/mat... Pin
YvesDaoust18-Oct-11 22:35
YvesDaoust18-Oct-11 22:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.