Skip to content

Instantly share code, notes, and snippets.

@dflima
Last active July 26, 2018 17:41
Show Gist options
  • Save dflima/444d4cd939c5d539d399dae312c61a08 to your computer and use it in GitHub Desktop.
Save dflima/444d4cd939c5d539d399dae312c61a08 to your computer and use it in GitHub Desktop.
using Tail Call Optimization pattern
defmodule Fibonacci do
def start(n) do
start = :os.system_time(:seconds)
fibonacciNumber = getNumber(n)
finish = :os.system_time(:seconds)
totalTime = finish - start
IO.puts("The fibonacci number was #{fibonacciNumber}")
IO.puts("Fibonacci for number placed #{n} finished in #{totalTime} seconds!")
end
def getNumber(n) when n < 0,
do: raise("You're trying to find a Fibonacci number under zero. Please try again")
def getNumber(n), do: getNumber(n, 1, 0)
defp getNumber(0, _, result), do: result
defp getNumber(n, next, result), do: getNumber(n - 1, next + result, next)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment