Check if an integer equals the sum of its digits to the fifth power I can do this in one line in Python:

sum([i for i in range(9,9999999) if i == sum([int(x)**5 for x  in str(i)])])


Not very fast, but works nicely. I thought it might be quicker to do it in Haskell, a language I'm quite new to:

-- helper func
toDigits    :: Int -&gt; [Int]
toDigits 0 = []
toDigits x = toDigits (x `div` 10) ++ [x `mod` 10]

isSumofFifth n = n == sum (map (^5) (toDigits n))
sum (filter isSumofFifth [9..9999999])


But it seems as slow, or even slower (I haven't done exact profiling).

I realise I could optimise it with a more refined upper bound, but aside from that, is there a better way to write this in Haskell?
I'm not familiar with either Haskell or Python, but I'd like to challenge the way you're tackling this problem.

First of all, seven 9s will give you a sum of 7 * 95 = 413343. That's six digits, so searching up to one million (instead of ten million) would already be enough.

But we can do better. Instead of analyzing all million numbers, you can reduce that number by realizing that 123456 will give the same sum as 654321. The order of the digits doesn't matter. The sums you actually need to compute are the combinations with repetition; there are 'only' 5005 of them. Python has a standard function to list them in the itertools package, e.g. combinations_with_replacement('0123456789', 6).

When you have computed the sum of the combination, you need to sort its digits and check if they match the combination. If so, the sum is a true positive and can be added to the list.