简体   繁体   中英

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

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

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

来自.Net 4.0+的BigInteger类支持任意大整数,int相对限制它代表的有效位数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM