Project Euler

 

I wanted to try my hand on solving the Project Euler problems. Here is my solution for the first problem.


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

I've been trying to learn Haskell for a long time, so here's my chance. Fortunately, this is surprisingly easy in Haskell.

sum [x | x <- [3..1000], mod x 3 ==0 || mod x 5 ==0]

Basically, what it does is sum up all the x, where x is from 3 to 1000, and where x is divisible by 3 or 5. There is also a simpler way of solving the problem.

sum ([3,6..1000]++[5,10..1000]) - sum[15,30..1000]

This sums up the multiples of 3 and multiples of 5, but since the multiples of 15 exists two lists (on the multiples of 3 as well as the multiples of 5), subtract one set of multiples of 15 so you get the correct value.

Published 02-12-2009 12:44 AM by jop
Filed under: ,