What is the sum of the digits of the number 2^1000?

前端 未结 10 1903
别跟我提以往
别跟我提以往 2021-01-02 03:13

This is a problem from Project Euler, and this question includes some source code, so consider this your spoiler alert, in case you are interested in solving it yourself. It

10条回答
  •  再見小時候
    2021-01-02 03:23

    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.

提交回复
热议问题