Skip to content

Instantly share code, notes, and snippets.

@reyou
Created May 24, 2018 02:16
Show Gist options
  • Save reyou/a9a2941c941457fe7d5f60ee2dea0115 to your computer and use it in GitHub Desktop.
Save reyou/a9a2941c941457fe7d5f60ee2dea0115 to your computer and use it in GitHub Desktop.
// find nth fibonacci both recursive and iterative
// 0 1 1 2 3 5 8 13 21
// 0 1 2 3 4 5 6 7 8
function fibo(nth) {
if (nth === 0) {
return 0;
}
if (nth === 1) {
return 1;
}
let firstResult = 1;
let secondResult = 0;
let result;
for (let i = 2; i <= nth; i++) {
result = firstResult + secondResult;
secondResult = firstResult;
firstResult = result;
}
return result;
}
console.log(fibo(6));
console.log(fibo(7));
console.log(fibo(8));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment