We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept

Find the factorial of a given number


Expectation

Factorial of a number n can be termed as multiplication of all numbers from 1 till the number n. n! = 1*2*3*...*n Example: 5!=1*2*3*4*5=120


Logic
        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


Loops •  Added 2 months ago

Sponsored Links