Skip to content

Instantly share code, notes, and snippets.

@Holajuwon
Created November 8, 2021 15:37
Show Gist options
  • Save Holajuwon/ad5b21cceab5163904171995ebd05e4b to your computer and use it in GitHub Desktop.
Save Holajuwon/ad5b21cceab5163904171995ebd05e4b to your computer and use it in GitHub Desktop.
// 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