Recently I started learning elixir for fun and as I’m new to programming in general it is not going too well.
Yesterday I found on the internet an exercise that required me to summarize all Fibonacci numbers less than 4_000_000. I tried doing it like that:
defmodule Fibonacci do
def fibonacci(number) do
Enum.reverse(fibonacci_do(number))
end
def fibonacci_do(1), do: [0]
def fibonacci_do(2), do: [1 | fibonacci_do(1)]
def fibonacci_do(number) when number > 2 do
[x, y | _] = all = fibonacci_do(number - 1)
[x + y | all]
end
end
defmodule Solve do
def lineOfFi(limit) do
fib_numbers = Fibonacci.fibonacci_do(limit)
Enum.sum(Enum.filter(fib_numbers, &(&1 < limit and rem(&1, 2) == 0)))
end
end
result = Solve.lineOfFi(4_000_000)
IO.puts(result)
The first part is code that I found on the internet (it was supposed to be fast), as calculating the sequence itself completely defeated me. Second part I based on a problem that I solved few days ago.
Unfortunately, this code contains a hidden bug or is so unoptimized that after 5 or 6 minutes of running, it crushes my computer.
I wonder what could be done to improve optimization of this code, that it will be possible to run it at all.