Created
November 8, 2021 15:37
-
-
Save Holajuwon/ad5b21cceab5163904171995ebd05e4b to your computer and use it in GitHub Desktop.
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
// solution 1 | |
function fibonacci(n){ | |
if(n < 2){ | |
return n; | |
} | |
// temporary variables | |
let prev = 0; | |
let curr = 1; | |
let arr = [0, 1]; | |
for(let i = 2; i <= n; i++){ | |
// add prev value to curr | |
const sum = prev + curr; | |
arr.push(sum) | |
console.log(prev, curr, sum) | |
// switch prev and curr values | |
prev = curr; | |
curr = sum; | |
} | |
console.log(arr) | |
return curr | |
} | |
// solution 2 | |
// Improvement after googling | |
function fibonacci2(n){ | |
if(n < 2){ | |
return n; | |
} | |
let arr = [0, 1]; | |
for(let i = 2; i <= n; i++){ | |
// save solutions | |
arr[i] = arr[i-1] + arr[i-2]; | |
console.log(arr) | |
} | |
return arr[n] | |
} | |
fibonacci2(6) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment