mirror of
https://github.com/correl/euler.git
synced 2024-11-23 19:19:53 +00:00
Excercise 002
This commit is contained in:
parent
4d2e456ece
commit
1cb2bacbbd
1 changed files with 52 additions and 0 deletions
52
e002.erl
Normal file
52
e002.erl
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
% Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
|
||||||
|
|
||||||
|
% 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(e002).
|
||||||
|
-export([
|
||||||
|
main/1,
|
||||||
|
fibonacci_max/1
|
||||||
|
]).
|
||||||
|
|
||||||
|
fibonacci_max(Max) ->
|
||||||
|
fibonacci_max_([], Max).
|
||||||
|
|
||||||
|
fibonacci_max_([], Max) ->
|
||||||
|
if
|
||||||
|
Max < 1 ->
|
||||||
|
[];
|
||||||
|
true ->
|
||||||
|
fibonacci_max_([1], Max)
|
||||||
|
end;
|
||||||
|
fibonacci_max_([N], Max) ->
|
||||||
|
Next = N + N,
|
||||||
|
if
|
||||||
|
Max < Next ->
|
||||||
|
[N];
|
||||||
|
true ->
|
||||||
|
fibonacci_max_([Next, N], Max)
|
||||||
|
end;
|
||||||
|
fibonacci_max_([N1, N2 | Seq], Max) ->
|
||||||
|
Next = N1 + N2,
|
||||||
|
if
|
||||||
|
Max < Next ->
|
||||||
|
[N1, N2 | Seq];
|
||||||
|
true ->
|
||||||
|
fibonacci_max_([Next, N1, N2 | Seq], Max)
|
||||||
|
end.
|
||||||
|
|
||||||
|
sum_if_even([]) ->
|
||||||
|
0;
|
||||||
|
sum_if_even([N | Seq]) ->
|
||||||
|
if
|
||||||
|
N rem 2 == 0 ->
|
||||||
|
N + sum_if_even(Seq);
|
||||||
|
true ->
|
||||||
|
sum_if_even(Seq)
|
||||||
|
end.
|
||||||
|
|
||||||
|
main(_) ->
|
||||||
|
Max = 4000000,
|
||||||
|
io:format("Sum for fibonacci <= ~w: ~w~n", [Max, sum_if_even(fibonacci_max(Max))]).
|
Loading…
Reference in a new issue