Project Euler Problem 030

Statement

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.

Solution

The key to get this solution is to determine when to stop. In a number of x digits the highest number
we can build up adding the digits elevated to y power is $9^y * x$ if this number is below
the original number then we will never be able to form numbers higher that these.

def sum_of_digits_to(i, n):
    return sum(int(c) ** n for c in str(i))
 
if __name__ == '__main__':
    n = 5
    limit = '9'
    while (9 ** n) * len(limit) > int(limit):
        limit += '9'
    limit = int(limit)
    result = 0
    for i in range(10, limit+1):
        if sum_of_digits_to(i, n) == i:
            result += i
    print("The result is:", result)

The Python file is available for download here

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License