Find the factorial of a given number

Factorial of a number n can be termed as multiplication of all numbers from 1 till the number n.

n! = 123*...*n

Example: 5!=12345=120

        public static double DoFactorial(long n)
        {
            // hardcode the simplest
            // 0! = 1
            // 1! = 1
            // 2! = 2

            if (n == 0)
            {
                return 1;
            }
            else if (n == 1)
            {
                return 1;
            }
            else if (n == 2)
            {
                return 2;
            }

            // n! = 1 * 2 * 3 * ... * n
            double nFactorial = 1;

            for (int i = 2; i <= n; i++)
            {
                nFactorial = nFactorial * i;
            }

            return nFactorial;
        }

How it works:

for n=5
nFactorial = 1, n=5
i = 1 => nFactorial = 1 * 1 = 1
i = 2 => nFactorial = 1 * 2 = 2
i = 3 => nFactorial = 2 * 3 = 6
i = 4 => nFactorial = 6 * 4 = 24
i = 5 => nFactorial = 24 * 5 = 120

which is the expected result


Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *