Select Page

#### Project Euler 16 Problem Statement

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the digit sum for the number 21000?

#### Solution

Python natively supports arbitrary-precision integers and arithmetic with as many digits as necessary to perform a calculation.  21000 requires 302 digits to represent this power and Python handles it easily.

To solve this problem we calculate 21000 and convert the result to a string so we can iterate over each character-digit (integers are not iterable, but strings are).

`sum(map(int, str(pow(2, 1000))))`

Then, using the `map` function we iterate over the string and convert every character-digit back to an integer using the `int` function.

Finally, we add them together using the `sum` function for a digit sum.

`sum(map(int, str(pow(2, 1000))))`

#### HackerRank version

HackerRank increases the exponent from 1,000 to 10,000 and runs 100 test cases.  This solution was fast enough to handle these parameters.

#### Last Word

Embrace the power of arbitrary-precision integers and ignore the call to solve it in some primitive way.