Project Euler Problem 16 Solution

Project Euler Problem 16 Solution

Power digit sum

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 16 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 ?


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 requires a little more scale by having you to solve up to 100 test cases with a higher limit for 2n, where n ≤ 10,000.

Python Source Code

n = int(input("2's exponent? "))
print ("Sum of the digits of 2 ^", n, " = ", sum(map(int, str(pow(2, n)))))	

Last Word

Using native language arbitrary–precision structures.

Simply embrace the power of arbitrary–precision integers and ignore the call to solve it in some primitive way. It’s evolution – get used to it.

See also, Project Euler 20: Factorial digit sum