Sandeep Chava
Sandeep Chava

Reputation: 35

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);
        }
    }
}

Upvotes: 3

Views: 975

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You have to use BigInteger in your solution:

using System.Numerics;
using System.Linq; 
...
int n = 95;

BigInteger factorial = Enumerable
  .Range(1, n)
  .Select(x => (BigInteger) x)
  .Aggregate((f, v) => f * v);

Console.WriteLine(factorial);

Answer is

10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000

note, that the factorial is far beyond long.MaxValue

Upvotes: 4

Micke
Micke

Reputation: 2309

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 . . .

Upvotes: 3

JSSchreiner
JSSchreiner

Reputation: 49

The BigInteger class from .Net 4.0+ supports arbitrarily large integers, int is relatively limiting in how many significant digits it represents.

Upvotes: 1

Related Questions