Created
May 24, 2017 11:45
-
-
Save ronaiza-cardoso/7232ac0b1a7a6c5092abf2fc2dbf416f to your computer and use it in GitHub Desktop.
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
function fib(n) { | |
// edge cases: | |
if (n === 0 || n === 1) | |
return n | |
/** | |
* we’ll be building the fibonacci series from the bottom up | |
* so we’ll need to track the previous 2 numbers at each step | |
**/ | |
let prevPrev = 0 // 0th fibonacci | |
let prev = 1 // 1st fibonacci | |
let current // Declare current | |
for (let i = 1; i < n; i++) { | |
// Iteration 1: current = 2nd fibonacci | |
// Iteration 2: current = 3rd fibonacci | |
// Iteration 3: current = 4th fibonacci | |
// To get nth fibonacci … do n-1 iterations. | |
current = prev + prevPrev | |
prevPrev = prev | |
prev = current | |
} | |
return current | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment