BigInteger cannot represent infinity

When I run this code I get a runtime 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 the values BigInteger

. So why is he throwing away OverflowException

?

+3


source to share


1 answer


This happened because you exceeded the limit for double

.

Math.Pow

evaluates to double

s, so the end result can only be 1.7e308 , the number you exceed for i = 144

. Thus, a result double.PositiveInfinity

that cannot be converted to BigInteger

. BigInteger

has no special representations for infinities as it does double

, it can only store integers, and infinity is not an integer, even if BigInteger

it has no limit, it will never reach infinity. In fact, there is also a limit BigInteger

when the internal array that it uses to store the number reaches its maximum size (memory may run out earlier).

In this case you can use BigInteger.Pow

to avoid it like



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

      

The result is quite large, as expected.

+11


source







All Articles