BigInteger cannot represent infinity

时间:2015-07-31 20:36:11

标签: c# algorithm biginteger

When i run this code I get run-time exception

OverflowException: BigInteger cannot represent infinity.

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

From what I understand there should be no limit to BigInteger values. So why it throws OverflowException?

1 个答案:

答案 0 :(得分:11)

This happened because you exceeded the limit for double.

Math.Pow there is evaluated in doubles, so a finite result can only be as big as about 1.7e308, a number you exceed for i = 144. So it results in double.PositiveInfinity, which cannot be converted to BigInteger. BigInteger has no special representations for infinities the way double does, it can only store integers and infinity is not an integer - even if BigInteger had no limit, it would never reach infinity. There is actually also a limit to BigInteger, when the internal array it uses to store the number reaches its maximum size (you may run out of memory sooner).

In this case you can use BigInteger.Pow to avoid this, for example

BigInteger sum = 0;
for (int i = 1; i <= 1000; i++)
    sum += BigInteger.Pow(i, i);

The result is quite big, as expected.