Normal int
can't help you with such a large number. Not even long
. They are never designed to handle numbers such huge. int
can store around 10 digits (exact max: 2,147,483,647
) and long
for around 19 digits (exact max: 9,223,372,036,854,775,807
). However, A quick calculation from built-in Windows calculator tells me 2^1000
is a number of more than 300 digits.
(side note: the exact value can be obtained from int.MAX_VALUE
and long.MAX_VALUE
respectively)
As you want precise sum of digits, even float
or double
types won't work because they only store significant digits for few to some tens of digits. (7
digit for float, 15-16
digits for double). Read here for more information about floating point representation, double precision
However, C# provides a built-in arithmetic
BigInteger
for arbitrary precision, which should suit your (testing) needs. i.e. can do arithmetic in any number of digits (Theoretically of course. In practice it is limited by memory of your physical machine really, and takes time too depending on your CPU power)
Back to your code, I think the problem is here
Math.Pow(2, powerOfTwo)
This overflows the calculation. Well, not really, but it is the double
precision is not precisely representing the actual value of the result, as I said.