Created
May 30, 2017 15:26
-
-
Save gabrielgodoy-zz/e05032302083ce4c74aa8956303bf135 to your computer and use it in GitHub Desktop.
Fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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