Skip to content

Instantly share code, notes, and snippets.

@kylethebaker
Last active July 23, 2017 01:57
Show Gist options
  • Save kylethebaker/f1859523941ddec46916a7a0d90b4164 to your computer and use it in GitHub Desktop.
Save kylethebaker/f1859523941ddec46916a7a0d90b4164 to your computer and use it in GitHub Desktop.
Erlang Fast Fibonacci
-module(fibonacci).
-export([fast_fib/1]).
-export([slow_fib/1]).
-spec slow_fib(integer()) -> integer().
-spec fast_fib(integer()) -> integer().
% Finds the Nth fibonacci number using standard recursion
% Gets unbearably slow to find around when N = 45
slow_fib(0) -> 0;
slow_fib(1) -> 1;
slow_fib(N) -> slow_fib(N - 1) + slow_fib(N - 2).
% Finds the Nth fibonacci number by counting up from 1 and adding the two
% previously found sums together
% Takes 10 seconds to find when N = 1,000,000
fast_fib(N) -> fast_fib(3, N, {1, 1}).
fast_fib(Step, Max, {_, X1}) when Step == Max + 1 -> X1;
fast_fib(Step, Max, {X0, X1}) -> fast_fib(Step + 1, Max, {X1, X0 + X1}).
@Ehbraheem
Copy link

Wow! This swept me off my feet. Don't tell me you're new to erlang

@Ehbraheem
Copy link

I would love to see your solution for the pieces problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment