In [ ]:
'''
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
'''
In [8]:
# find bounds: for example, smallest 5 digit number: 10000
# fifth power
# sum is 1^5 = 1
# maximum sum is 5 * 9**5
# 5 * 9**5
# 295245
# 6 digits: 100000
# 7 digits: 1 000 000 = 10**(digits - 1)
# 7 * 9**5 # (digits) * 9**(power)
# 413343
# so no seven digit number can be expressed as a sum of the fifth powers of its digits, because the highest possible sum
# for 9999999 is less than 7 digits
# so lets define a boundary first
def findNumsAsPowers(power):
'''Returns a set of numbers which can be expressed as the sum of the power-th power of their digits.'''
nums = set()
i = 1 # i is the number of digits in our number, which we have to put a limit on
while ((10**(i-1)) < (i * (9**power))):
i += 1
# now use i as a limit
for j in range(2, (10**(i-1))):
ints = [int(k) for k in str(j)] # split the number into digits
powersum = sum((l**power) for l in ints) # calculate power sum
if powersum == j: # save if digit power sum equals the number
nums.add(j)
return(nums)
In [11]:
sum(findNumsAsPowers(5))
Out[11]: