Last active
August 29, 2015 13:55
-
-
Save l0gicpath/8726032 to your computer and use it in GitHub Desktop.
Project Euler Problem #2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(problem_2). | |
-export([solve/1]). | |
-define(LIMIT, 4000000). | |
%% Normalizing the start value, need to start with an odd value and enter tail recursion | |
solve(Start) when Start rem 2 == 0, Start > 0 -> solve(Start - 1, Start, 0); | |
solve(Start) -> solve(Start, Start + 1, 0). | |
%% guard against the limit and drop out of recursion if we hit it | |
solve(Prev, Next, Sum) when Prev >= ?LIMIT; Next >= ?LIMIT -> Sum; | |
%% Sum even values | |
solve(Prev, Next, Sum) when Next rem 2 == 0 -> solve(Next, Prev + Next, Sum + Next); | |
%% Move onto the next value in the fib series | |
solve(Prev, Next, Sum) -> solve(Next, Prev + Next, Sum). | |
% To run it, you'll need Erlang ofcourse.. Duh. R15+ would do just fine | |
% From your terminal, compile | |
% $ erlc problem_2.erl | |
% Pop open erlang's shell | |
% $ erl | |
% Have fun | |
% > problem_2:solve(1). | |
%% Change Log: | |
%% - revision 1: solution per specs. | |
%% - revision 2: an unused variable slipped through the cracks, removed it. | |
%% - revision 3: covered a case of which the start variable isn't odd, only other way to cover such case is with another guard | |
%% on Prev which will eventually give us an off by -Next-value- error. | |
%% - revision 4: fixed a typo. Note to self: this was a rather shit idea to hack on a code snippet at 5am after a sprint |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment