Given a positive integer n, find the nth Fibonacci number. Fibonacci numbers, when it starts from 0, are calculaed as F(n), where F(1) = 0, F(2) = 1, and F(n) = F(n-1) + F(n-2) for n > 2. Example of first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
This algorithm uses memoization to improve performance. It's same as the recursive version of Fibonacci, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:
cache = {} def fib(n): if n < 2: return 0 if n == 2: return 1 if n not in cache: cache[n] = fib(n - 1) + fib(n - 2) return cache[n] n = 5 print(fib(n))
const cache = {} function fib(n) { if (n < 2) { return 0; } if (n == 2) { return 1; } if (cache[n] === undefined) { cache[n] = fib(n - 1) + fib(n - 2); } return cache[n]; } const n = 5; console.log(fib(n));