Last active
November 23, 2016 03:18
-
-
Save marclundgren/ceb14b7c81492356d65c2683b9c2160e to your computer and use it in GitHub Desktop.
fibonacci algorithms (recursive and iterative)
This file contains 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
function fib(num) { | |
if (num === 0) { | |
return 0 | |
} | |
if (num === 1 || num === 2) { | |
return 1 | |
} | |
let a = 1 | |
let b = 1 | |
for (let index = 3; index < num; index++) { | |
[a,b] = [a + b, a] | |
} | |
return a + b | |
} |
This file contains 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
function fibRecursive(num) { | |
if (num === 0) { | |
return 0 | |
} | |
if (num === 1 || num === 2) { | |
return 1 | |
} | |
return fibRecursive(num - 1) + fibRecursive(num - 2) | |
} |
todo: i can replace the temporary variable with this pattern: https://files.slack.com/files-pri/T04KHD82U-F2TEYNB26/pasted_image_at_2016_10_24_10_31_am.png
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
recursive: O(2^n)
http://stackoverflow.com/a/13440108/6307603