Skip to content

Instantly share code, notes, and snippets.

@rcdilorenzo
Last active February 17, 2016 17:19
Show Gist options
  • Save rcdilorenzo/d472e633cefb2bbb85d5 to your computer and use it in GitHub Desktop.
Save rcdilorenzo/d472e633cefb2bbb85d5 to your computer and use it in GitHub Desktop.
defmodule Standard do
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(n-1) + fib(n-2)
end
defmodule Optimized do
def fib(0), do: 0
def fib(1), do: 1
def fib(1, current, _), do: current
def fib(n, current \\ 1, previous \\ 0) do
fib(n - 1, current + previous, current)
end
end
defmodule Matrix do
def fib(n) do
eigen1 = (1 + :math.sqrt(5))/2
eigen2 = (1 - :math.sqrt(5))/2
((1 / :math.sqrt(5)) * (:math.pow(eigen1, n) - :math.pow(eigen2, n)))
end
end
:eprof.start
:eprof.start_profiling([self])
Standard.fib(20)
Optimized.fib(20)
Matrix.fib(20)
:eprof.stop_profiling()
:eprof.analyze()
# ****** Process <0.48.0> -- 100.00 % of profiled time ***
# FUNCTION CALLS % TIME [uS / CALLS]
# -------- ----- --- ---- [----------]
# 'Elixir.Matrix':fib/1 1 0.03 1 [ 1.00]
# 'Elixir.Optimized':fib/3 20 0.05 2 [ 0.10]
# 'Elixir.Standard':fib/1 21891 99.34 3636 [ 0.17]
function fib(n) {
return n <= 2 ? 1 : fib(n-2) + fib(n-1);
}
- (NSUInteger)fib:(NSUInteger)n {
if (n < 2) {
return 1;
}
return [self fib:(n - 1)] + [self fib:(n - 2)];
}
function fib($n) {
if ($n <= 2) {
return 1;
}
return fib($n - 2) + fib($n - 1);
}
def fib(n)
return 1 if n <= 2
fib(n - 2) + fib(n - 1)
end
func fib(n: Int) -> Int {
return n <= 2 ? 1 : fib(n - 2) + fib(n - 1)
}
fib(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment