Thursday, January 8, 2009

Erlang solution to Euler problem 2

Once you have solved a problem and entered the correct answer on the project Euler website it gives you access to a PDF file and a discussion thread which discusses possible solutions to that problem. I won't give away any hints, but it turns out that there is a much better way to solve problem 1 than the brute force approach which my program used. It looks like I might not only learn Erlang but also a thing or two about math...

Since it didn't take much time to come up with a solution for problem 1, I decided to do problem 2 today as well. Here is what I came up with:

-module(euler2).

-export([solve/0, solve/1]).

solve() ->
solve(4000000).

solve(Max) ->
solve(Max, 1, 1, 0).

solve(Max, Current, Prev, Total) ->
if
Current > Max ->
Total;
Current rem 2 == 0 ->
solve(Max, Current+Prev, Current, Total+Current);
true ->
solve(Max, Current+Prev, Current, Total)
end.

No comments: