Skip to content

Instantly share code, notes, and snippets.

@esobchenko
Created September 10, 2009 13:55
Show Gist options
  • Save esobchenko/184564 to your computer and use it in GitHub Desktop.
Save esobchenko/184564 to your computer and use it in GitHub Desktop.
project euler: problem solutions
-module(euler).
-compile(export_all).
%% problem 1
%% If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
%% Find the sum of all the multiples of 3 or 5 below 1000.
%% Answer: 233168
sum_of_multiples(Sum, N, Max) ->
Is_multiple = fun(X) -> (X rem 3) =:= 0 orelse (X rem 5) =:= 0 end,
case N < Max of
false -> Sum;
true ->
case Is_multiple(N) of
true -> sum_of_multiples(Sum+N, N+1, Max);
false -> sum_of_multiples(Sum, N+1, Max)
end
end.
problem_1() -> sum_of_multiples(0, 1, 1000).
%% problem 2
%% 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.
%% Answer: 4613732
fib(1) -> 1;
fib(2) -> 2;
fib(N) when N > 2 -> fib(N-1) + fib(N-2).
is_even(N) when is_integer(N) -> (N rem 2) =:= 0.
sum_of_even_fib_terms(Sum, N, Max) ->
Term = fib(N),
case Term < Max of
false -> Sum;
true ->
case is_even(Term) of
false -> sum_of_even_fib_terms(Sum, N+1, Max);
true -> sum_of_even_fib_terms(Sum+Term, N+1, Max)
end
end.
problem_2() -> sum_of_even_fib_terms(0, 1, 4000000).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment