How I beat Project Euler using Erlang: Christmas Edition, problem one

Merry Christmas everyone!

It’s been a long time since I wrote a post, but I’ve been very busy coding, and I could only muster some posts for Stacktrace, so express all your Christmas-y goodness and pardon me :)

On Stacktrace we just started posting in depth analysis of the Project Euler problems, and I decided to try and solve them using Erlang, since I already did using Ruby a couple of years ago.

The first problem is quite simple:

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 will not try to give you the clever solution since this problem is quite simple, and the brute force solutions works fine :)

-module(p1). 
-export([sum_mul/1]). 
 
sum_mul([H|T]) -> valid(H) + sum_mul(T);
sum_mul([]) -> 0.
valid(H) when H rem 3 =:= 0; H rem 5 =:= 0 -> H;
valid(H) -> 0.

To get the solution just call _sum_mul(lists:seq(1,999))_.

Have a Merry Erlang Christmas!

Comments are closed.