BigInteger不能代表无限

LCT*_*CTS 3 c# algorithm biginteger

当我运行此代码时,我得到运行时异常

OverflowException:BigInteger不能表示无穷大.

BigInteger sum=0;
for (double i=1 ; i<=1000 ;i++ )
    sum += (BigInteger) Math.Pow(i,i);
Console.WriteLine(sum);
Run Code Online (Sandbox Code Playgroud)

据我所知,BigInteger价值观应该没有限制.那它为什么会抛出OverflowException

har*_*old 11

这是因为你超过了限制double.

Math.Powdoubles 中进行评估,因此有限的结果只能达到大约1.7e308,这个数字超过了i = 144.所以它导致double.PositiveInfinity,无法转换为BigInteger.BigInteger对于无穷大没有特殊的表示方式double,它只能存储整数,无穷大不是整数 - 即使BigInteger没有限制,它也永远不会达到无穷大.BigInteger当用于存储数字的内部数组达到其最大大小时,实际上也有一个限制(您可能会更快地耗尽内存).

例如,在这种情况下,您可以使用它BigInteger.Pow来避免这种情况

BigInteger sum = 0;
for (int i = 1; i <= 1000; i++)
    sum += BigInteger.Pow(i, i);
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,结果非常大.