Skip to content

Instantly share code, notes, and snippets.

@gabrielgodoy-zz
Created May 30, 2017 15:26
Show Gist options
  • Save gabrielgodoy-zz/e05032302083ce4c74aa8956303bf135 to your computer and use it in GitHub Desktop.
Save gabrielgodoy-zz/e05032302083ce4c74aa8956303bf135 to your computer and use it in GitHub Desktop.
Fibonacci
/*
Slow way
*/
var utils = {
fibonacci: function(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
} else {
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}
};
/*
Fast way
If you don't have an Array then you save on memory and .push calls
*/
var utils = {
fibonacci: function(n) {
var a = 0,
b = 1,
c;
if (n < 3) {
if (n < 0) return fib(-n);
if (n === 0) return 0;
return 1;
}
while (--n) {
c = a + b, a = b, b = c;
}
return c;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment