javascript-algorithms icon indicating copy to clipboard operation
javascript-algorithms copied to clipboard

added recursion (fib) with caching

Open TheWebDevel opened this issue 5 years ago • 0 comments

Added recursion with caching (for fib) to avoid recomputing the already computed value. Example: console.log(fibonacci_with_caching(500));

Sorry about my VS Code prettier formatting the file. LMK if I need to change anything. :)

//Write a recursive function fib with caching
let cache = {};
function fibonacci_with_caching(n) {
  // Base Case
  if (n <= 1) {
    return n;
  }

  if (cache[n]) {
    return cache[n];
  }
  cache[n] = fibonacci_with_caching(n - 1) + fibonacci_with_caching(n - 2);
  return cache[n];
}

console.log(fibonacci_with_caching(1));
console.log(fibonacci_with_caching(4));
console.log(fibonacci_with_caching(10));
console.log(fibonacci_with_caching(28));
console.log(fibonacci_with_caching(35));
console.log(fibonacci_with_caching(500));

TheWebDevel avatar Oct 02 '20 01:10 TheWebDevel