Project Euler 16: Sum of the digits in the number 2^1000
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
Python supports arbitrary precision integers so calculating any obscenely large number can be done without external libraries.
Calculate 21000, split the digits and add them together. The
str() function is used as an iterator and serves each character in 21000 until it reaches the end of the string.
I’m sure when this problem was created it was intended to be solved without large integer support or string manipulations, but such is the way of modern languages.
Project Euler 16 SolutionRuns < 0.001 seconds in Python 2.7.
Use this link to get the Project Euler 16 Solution Python 2.7 source.
AnswerSlowly swipe from either end beginning with the white vertical bar to get an idea of the starting or ending digits. For less drama, just double click the answer area. The distance between the two bars will give you an idea of the magnitude. Touch devices can tap and hold the center of the box between the two bars and choose define to reveal the answer.
- See also, Project Euler 20 Solution: Find the sum of the digits in 100!
- If you were doing something like this a lot on non-negative integers, then the following function might serve you better:
def sum_of_digits(n): r = 0 n = int(abs(n)) while n: r, n = r + n % 10, n / 10 return r