Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
60 lines (43 sloc) 1.33 KB
%% Problem
%% ---------------------
%% Each new term in the Fibonacci sequence is generated by adding the previous two terms.
%% By starting with 1 and 2, the first 10 terms will be:
%% 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
%%
%% Find the sum of all the even-valued terms in the sequence which do not exceed four million.
%% ---------------------
-module(p002).
-export([solve1/0, solve2/0, solve3/0]).
%% Solution 1
%% ---------------------
%% Basic brute force
%% ---------------------
solve1() -> fib(4000000).
fib(Max) ->
fib(1, 1, Max).
fib(Fst, Snd, Max) ->
fib(Fst, Snd, Max, 0).
fib(_Fst, Snd, Max, Acc) when Snd > Max ->
Acc;
fib(Fst, Snd, Max, Acc) when Snd rem 2 =:= 0 ->
fib(Snd, Fst+Snd, Max, Acc+Snd);
fib(Fst, Snd, Max, Acc) ->
fib(Snd, Fst+Snd, Max, Acc).
%% Solution 2
%% ---------------------
%% Found on Euler forum
%% ---------------------
solve2() -> fse(4000000).
fse(Max) -> fse({1, 1}, Max, 0).
fse({P1, P2}, Max, T) when (P1 + P2) < Max ->
fse({P1 + 2 * P2, 2 * P1 + 3 * P2}, Max, T + P1 + P2);
fse({P1, P2}, Max, T) when (P1 + P2) >= Max -> T.
%% Solution 3
%% ---------------------
%% 2 8 34 144...
%% E(n) = 4*E(n-1) + E(n-2)
%% ---------------------
solve3() -> f(4000000).
f(M) -> f(2, 8, M, 10).
f(A, B, Max, R) when A + 4*B > Max -> R;
f(A, B, Max, R) -> f(B, A + 4*B, Max, R + A + 4*B).