Project Euler n°1 in Haskell

Posted on September 2, 2020
Tags: Python, Haskell, Programming

The 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.


Classic solution in Python:

list_of_multiples = []

for x in range(1, 1000):
    if x%3 == 0 or x%5 == 0:
        list_of_multiples.append(x)

print(sum(list_of_multiples))

Still Python but with list comprehension

sum([x for x in range(1, 1000) if x%3 == 0 or x%5 == 0])

And finally in Haskell (there surely is a better solutions but hey, I’m learning):

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