Problem 5

The 5th problem of the project_euler was the first one that gave me some work, mainly because I started (again) by trying a brute force algorithm. Of course, I had problems with it, starting by not getting the solution at all!! It just took too much time to calculate it and I did not let it finish. I tried different values as input, but it was not enough. Here is the code I used:

    f [] = 0 f (x:xs) =
      if condition x then x else f xs

    condition :: Int -> Bool
    condition = foldr (&&) True . apply
      where apply n = [ mod n x == 0 | x <- [1..20]]

As you can see, I needed to give a list as input for the function f and be lucky enough to have the correct value within that list. After a few tries, I decided to think a bit more in the problem and searching a bit in the Haskell Prelude and I came across with the lcm function, which allowed me to solve this problem very efficiently:

    g = foldr lcm 1 [1..20]

Published: October 31 2009

blog comments powered by Disqus