Back to Project Euler

Previous Problem Next Problem

Problem 30: Digit Fifth Powers

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+44

As 1=14 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

Let f(n) be the sum of the fifth powers of the digits of n. The maximum value of f for any k-digit number is 95k=59049k, and the minimum value of any k-digit number is 10k1. Because 59049k<10k1 for k7, f(n)<n for n106; and because f(n)95×6=354294 for n<106, f(n)<n for n354295. This considerably cuts down on the values we have to check, even if we have to check those values by force.

Python Code

def p30():
	res = 0
	for n in range(2, 354294):
		ds, n_copy = 0, n
		while n_copy > 0:
			ds += (n_copy % 10) ** 5
			n_copy //= 10
		if ds == n:
			res += n
	return res

Previous Problem Next Problem

Back to Project Euler