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
?
This happened because you exceeded the limit for double
.
Math.Pow
there is evaluated in double
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With