Project Euler Problem 16 Solution

Project Euler Problem 16 Solution

Power digit sum

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 16 Statement

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

What is the digit sum for the number $2^{1000}$?

Solution

Using arbitrary–precision integer arithmetic

print(sum(map(int, str(pow(2, 1000)))))
Text with a dashed underscore will highlight the code section being talked about when moused over or tapped.

Python natively supports arbitrary–precision integers and arithmetic using as many digits as there is available memory to perform a calculation. We use that feature to our full advantage to provide a simple solution to this problem.

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

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 calculate a digit sum by adding them together using the sum function.

HackerRank version

HackerRank Project Euler 16 involves solving up to 100 test cases with with $2^N$, where $1\le N\le 10^4$.

Python Source Code

for _ in range(int(input())):
    N = int(input())
    print(sum(map(int, str(2**N))))	

Last Word

See also, Project Euler 20: Factorial digit sum

"Old School" without Python arbitrary–precision integers

We can calculate the powers of $2$ by successively multiplying each power (starting with $1$) by $2$, and generating the series $1, 2, 4, 8, 16, 32 \dots 2^{1000}$. Each power is broken apart digit-by-digit and pushed onto the list, digits[]. This will result in the power being stored in reverse order, but that doesn't affect the digit-sum.

Pay attention to how the variable carry works in this algorithm; it can have only values of $0$ or $1$. Each carry with a value of $1$ indicates a new decimal magnitude transition such as $2^6=64$ to $2^7=128$, $2^9=512$ to $2^{10}=1024$, and so on.

This serves an important purpose: It increases the length of the list by appending a one to the end which acts as a placeholder for the next power of $2$.

n = int(input("2's exponent? "))
digits = [1]
for _ in range(n):
    carry = 0;
    for i,dx in enumerate(digits):
        d = 2*dx + carry
        carry, digits[i] = divmod(d,10)
    if carry>0:
        digits.append(1)
print("Sum of the digits of 2 ^", n, " = ", sum(digits))