views:

208

answers:

1

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 in n
  • sf (n) is the sum of the digits in the result of f (n)
  • g (i) is the smallest integer solution for sf (i). As there can be many results for sf (i)
  • sg (i) is the sum of the digits in the result of g (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.

+2  A: 

The memory problem might lie in decToList or fac.

I ran it with

fac = product . enumFromTo 1
decToList = map (read . return) . show
main = print answer

And it didn't come near to sucking all my RAM, it did not finish, though.

btw: I suspect an advanced project Euler problem to be harder than that. therefore this algorithm won't do.

yairchu
The factorial and decimal to list functions in this problem are trivial i guess, unless the value for g(i) becomes incredibly large.But it seemed so simple! Perhaps I'll ask my maths teachers and that chemistry teacher who is also an ace at computer science tomorrow.
Jonno_FTW
@Jonno_FTW: Even though they are trivial, for debugging a mysterious bug, one requires the complete picture
yairchu