Skip to content

Instantly share code, notes, and snippets.

@ronaiza-cardoso
Created May 24, 2017 11:45
Show Gist options
  • Save ronaiza-cardoso/7232ac0b1a7a6c5092abf2fc2dbf416f to your computer and use it in GitHub Desktop.
Save ronaiza-cardoso/7232ac0b1a7a6c5092abf2fc2dbf416f to your computer and use it in GitHub Desktop.
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