Skip to content

Problem 5

October 31, 2009

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]

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: