Project Euler Problem 16 Solution

Project Euler & HackerRank Problem 16 Solution

Power digit sum
by {BetaProjects} | FEBRUARY 15, 2009 | 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)))))

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 of n ≤ 10,000.

Python Source

download Python source code Use this link to download the Project Euler Problem 16: Power digit sum.

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 use to it.

See also, Project Euler 20: Factorial digit sum