Konbor704

Konbor704

Fibonacci sequence that turns off computer.

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.

Most Liked

technusm1

technusm1

Welcome to Elixir community @Konbor704, the problem here is that this code is trying to calculate 4 million fibonacci numbers, NOT fibonacci numbers less than 4_000_000.
See this line:

fib_numbers = Fibonacci.fibonacci_do(limit)

So, your Elixir program is doing a long computation because Fibonacci numbers tend to grow very fast.

If you want to calculate fibonacci numbers, you can use the Stream and Enum modules, specifically look at Stream.unfold:

# This one-liner creates an infinite "list" of numbers from
# which you can extract as many numbers as you want.
# The elements will be calculated on-demand by calling
# the passed function
Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)

Now if you want the first 100 Fibonacci numbers, you can do:

Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
|> Enum.take(100)

If you want all fibonacci numbers less than 4 million, you can do:

Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
|> Enum.take_while(fn number -> number < 4_000_000 end)

Further, if you want to sum the numbers, you can pipe the above output to Enum.sum.

Enjoy learning Elixir and have fun solving problems. :slight_smile:

EDIT: I would also suggest looking at the Elixir pipe operator ( |> operator). It is one of the most loved features of Elixir and you’ll soon find out how you can improve your code to make it more readable and how it also helps to understand the parameter positions for a function in a given module (thus allowing you to easily understand and making it easier to memorize standard library module functions!)

Konbor704

Konbor704

Thank you so much for explanation.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

We're in Beta

About us Mission Statement