I've written a simple Haskell program to solve a puzzle. The algorithm is correct and it produces the correct result for n = 40
, which is 14466. However, for n = 100
the program gets so slow that I haven't even been patient enough to wait it out.
I don't understand why it's so slow, since I would expect it to cache all the results for the intermediate function calls, you know, with Haskell being a lazy language and all.
My Compiler is GHCi 7.6.3.
I've tried profiling, but this just tells me that 99.9% of the time is spent in the isLoosing function.
isLoosing :: Int -> Int -> Bool
isLoosing x y
| y < x = isLoosing y x
| x == 0 = True
| x == 1 = False
| y `mod` x == 0 = False
| otherwise = and [ not (isLoosing (y-x*m) x) |
m <- [1..(y `div` x)] ]
loosingSum :: Int -> Int
loosingSum n = sum [ x + y |
x <- [1..(n-1)],
y <- [(x+1)..n],
isLoosing x y == True ]
main = print $ loosingSum 40