Euler problem 30

Haskell

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. 

——————————

sum_5th_powers n = sum $ map ((^5) . digitToInt) (show n)

-- sum_5th_powers 999999 == 354294
-- sum_5th_powers 9999999 == 413343

For a number having more than 6 digits, the fifth powers of its digits cannot be the number itself. So we should consider only numbers with less than 7 digits.

-- sum_5th_powers ______ <= 354294

For the numbers not greater than 354294, the number whose sum_5th_powers can represent the largest number is …

When 2 –> 1, in exchange for 4 –> 9, we earn — we get 354199;
When 4 –> 3, in exchange for 1 –> 9, we earn — we get 353999;
When 5 –> 4, in exchange for 3 –> 9, we earn — we get 349999;
When 3 –> 2, in exchange for 4 –> 9, we earn — we get 299999.

So the maximum number sum_5th_powers can represent is …

-- sum_5th_powers 299999 == 295277

-- 295277
-- 199999

-- sum_5th_powers 199999 == 295246

p30 = [n | n <- [10..m], n == sum_5th_powers n]
    where m = 295246

——————————

— Me@2015-07-06 08:42:07 PM

2015.07.07 Tuesday (c) All rights reserved by ACHK