Hi
I am trying to do problem 254 in project euler and arrived at this set of functions and refactor in Haskell:
f n = sum $ map fac (decToList n)
sf n = sum $ decToList (f n)
g i = head [ n | n <- [1..], sf n == i]
sg i = sum $ decToList (g i)
answer = sum [ sg i | i <- [1 .. 150] ]
Where:
f (n)
finds the sum of the factorials of each digit inn
sf (n)
is the sum of the digits in the result off (n)
g (i)
is the smallest integer solution forsf (i)
. As there can be many results forsf (i)
sg (i)
is the sum of the digits in the result ofg (i)
But not long into running the compiled version of this script, it sucked up all my RAM. Is there a better way to implement the function g (i)
? If so what can they be and how could I go about it?
EDIT:
Just out of clarity, my functions for:
fac
is :
`fac 0 = 1`
`fac n = n * fac (n-1)`
decToList
which makes a number into a list:
decToList1 x = reverse $ decToList' x
where
decToList' 0 = []
decToList' y = let (a,b) = quotRem y 10 in [b] ++ decToList' a
Although I did since update them to Yairchu's solution for optimisation sake.