Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger cannot represent infinity

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?

like image 757
LCTS Avatar asked Dec 10 '22 21:12

LCTS


1 Answers

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.

like image 154
harold Avatar answered Dec 13 '22 10:12

harold