Skip to content

Instantly share code, notes, and snippets.

@fschuindt
Last active August 24, 2017 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fschuindt/525643703ad4aba8852cf897553d13f3 to your computer and use it in GitHub Desktop.
Save fschuindt/525643703ad4aba8852cf897553d13f3 to your computer and use it in GitHub Desktop.

Concurrent calculation of Fibonacci in Elixir up to the 1200th position (faster than you can see)

It uses a known formla to evaluate a position instead of calculating it in a sequencial and/or recursive approach.
Formula

It's amazing how fast it is:
Demonstration

defmodule ConcurrentFibonacci do
def start do
parallel_map(1..1200, fn(x) ->
"Fibonacci of #{x} is: #{FibonacciCalculus.of(x)}"
end)
end
def parallel_map(list, func) do
list |> Enum.map(fn e -> spawn(fn ->
IO.puts func.(e)
end) end)
end
end
defmodule FibonacciCalculus do
@golden_n :math.sqrt(5)
def of(n) do
(x_of(n) - y_of(n)) / @golden_n
end
def x_of(n) do
:math.pow((1 + @golden_n) / 2, n)
end
def y_of(n) do
:math.pow((1 - @golden_n) / 2, n)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment