Search code examples
c#typesfactorial

Print 95 factorial as a number and not as exponential function


When the input is 25 the expected output is 15511210043330985984000000 and not 1.551121e+25. The parsing though is solved by Decimal.Parse(factorial.ToString(), System.Globalization.NumberStyles.Float).

I cannot get to calcuate for bigger numbers like 95.

using System;

namespace bigNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = Convert.ToInt32(Console.ReadLine());
            long factorial = 1;

            for (int i = number; i > 0; i--)
            {
                factorial = factorial * i;
            }

            Console.WriteLine(factorial);
        }
    }
}

Solution

  • As stated above, the BigInteger is a good candidate, as it can hold an arbitrarily large signed integer:

    namespace ConsoleApplication4
    {
        using System;
        using System.Numerics;
    
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(Factorial(0));
    
                Console.WriteLine(Factorial(25));
    
                Console.WriteLine(Factorial(95));
            }
    
            private static BigInteger Factorial(int number)
            {
                BigInteger factorial = 1;
    
                for (var i = number; i > 0; i--)
                {
                    factorial *= i;
                }
    
                return factorial;
            }
        }
    }
    

    1
    15511210043330985984000000
    10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000
    Press any key to continue . . .