Published: March 11, 2024

Project Euler

Problem 30 - Digit Fifth Powers

Problem

This problem comes from Project Euler 30

Problem

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634=14+64+34+448208=84+24+04+849474=94+44+74+441634 = 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=141 = 1^4 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19 316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

Solution

This problem is interesting because it doesn’t mention a scope. How do we know when to stop searching for numbers that can be written as the sum of the fourth/fifth power of their digits? I don’t know myself, but I made some assumptions.

In the problem there four digits that can be raised to the fourth power. So the range for this problem would be 4×94=94+94+94+944 \times 9^4 = 9^4 + 9^4 + 9^4 + 9^4 . So by that, our maximum search would be 5×955 \times 9^5 .

With that assumption made, we’ll go through each number as the problem states and find the numbers that are sums of their digits raised to the fifth power.

Code

# Project Euler: Problem 30
# Digit Fifth Powers

n = 5
search_range = n*(9**n)
sum_digits = 0

for number in range(2, search_range):
    num = [int(i) for i in str(number)]
    result = sum(map(lambda i: i**n, num))

    if result == number:
        sum_digits += number

    # This block is optional
    # For no apparent reason it allows the code
    # to execute on my computer ~200ms faster
    if result > search_range:
        break

print(sum_digits)

Also note the mysterious, “useless” code. Yep, without it my code takes ~770ms to execute, and with it it takes ~530ms to execute. No idea why.