Getting started with my quest via my first attempt at a solution in Erlang to Project Euler’s problem number 1.
The problem itself is simply stated : “Find the sum of all the multiples of 3 or 5 below 1000.”
A naive algorithm is immediately apparent- cycle through each number between below 1000 and sum those that are evenly divisible by 5 or 3. While hardly sophisticated or efficient, it’s an algorithm that will work.
In thinking about how to do this in a functional language like Erlang, it seems the obvious approach is recursion. A function that takes a number N as an input and calls itself for N-1, adding N to the result of the recursive call if N is evenly divisible by 3 or 5. I also decided to make the determination if N was a 3 or 5 multiple its own function.
So conceptually, the answer and the approach came pretty quickly. I stumbled a bit on implementation mostly due to not understanding Erlang’s if-statement at all. Once I sussed out the oddities there (including not being able to call a function in a guard expression- this puzzles me, but I also get the feeling that understanding why this is true is important to my grokking Erlang. I must explore further), the functions fell into place and I had a tiny understanding of how to start thinking about this sort of thing.
It’s been too long for me. Tiny little baby steps needed. I could have written this in a C-like language as fast as I can type. This took a bit longer.
My magnificent code for Problem 1.
-module(euler1).
-export([sumof3and5multiples/1]).
sumof3and5multiples(0)->
0;
sumof3and5multiples(N) ->
Multiple = ismultipleof3or5(N),
if
Multiple == true ->
N + sumof3and5multiples(N-1);
true ->
sumof3and5multiples(N-1)
end.
ismultipleof3or5(X) ->
if
X rem 3 == 0 ->
true;
X rem 5 == 0 ->
true;
true ->
false
end.

Post a Comment