From dd2a6d02a75075a149d8463a8212aa883999845e Mon Sep 17 00:00:00 2001 From: David Kerkeslager Date: Tue, 13 Dec 2016 09:45:38 -0500 Subject: [PATCH] Solved project euler 2 --- euler/elixir/0002-sum-of-fibonacci.exs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 euler/elixir/0002-sum-of-fibonacci.exs diff --git a/euler/elixir/0002-sum-of-fibonacci.exs b/euler/elixir/0002-sum-of-fibonacci.exs new file mode 100644 index 0000000..350ef01 --- /dev/null +++ b/euler/elixir/0002-sum-of-fibonacci.exs @@ -0,0 +1,20 @@ +defmodule SumOfEvenFibonacci do + def fibonacci_stream() do + items_with_prev = Stream.iterate({0,1}, fn({prev, curr}) -> {curr, prev + curr} end) + Stream.map(items_with_prev, fn({_, curr}) -> curr end) + end + + def fibonacci_to(limit) do + Stream.take_while(fibonacci_stream(), fn(n) -> n < limit end) + end + + def filter_even(stream) do + Stream.filter(stream, fn(n) -> rem(n, 2) == 0 end) + end + + def even_fibonacci_to(limit) do + filter_even(fibonacci_to(limit)) + end +end + +IO.inspect(Enum.sum(SumOfEvenFibonacci.even_fibonacci_to(4_000_000))) -- 2.20.1