打印95的阶乘作为一个数字,而不是指数函数

本文关键字:数字 一个 指数函数 阶乘 打印 | 更新日期: 2023-09-27 18:11:40

当输入为25时,期望输出为15511210043330985984000000而不是1.551121e+25。解析方法由Decimal.Parse(factorial.ToString(), System.Globalization.NumberStyles.Float)解决。

我不能计算像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);
        }
    }
}

打印95的阶乘作为一个数字,而不是指数函数

您必须在解决方案中使用BigInteger:

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);
回答是

10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000

注意,factorial远远超过 long.MaxValue

如上所述,BigInteger是一个很好的选择,因为它可以保存任意大的有符号整数:

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表示的有效数字数量相对有限。