Bottom Up Fibonacci (JS)

PHOTO EMBED

Mon Oct 18 2021 14:22:52 GMT+0000 (Coordinated Universal Time)

Saved by @Adorism80 #javascript

const bottomUpFib = function(n) {
  if (n < 2) return n
  
  const cache = [0,1]
  
  for (let i=2; i<= n; i++) {
    cache[i] = cache[i-1] + cache[i-2]
    console.log(`Iteration ${i} ---> \n
                Cache ${cache}\n`)
  }
return cache[n]
}

console.log(bottomUpFib(5))

//If you go to a more complicated problem, you might need to build a 2d array or matrix and you need to find the solution. Each index in the array, corresponds to a solution to a sub-fib problem. You are creating a lookup table. This is what makes dynamic programming so cool
content_copyCOPY