LearnFrenzy
Sign in Take a free test

Functions · Functions Coding Problems · Question 5

Memoized Fibonacci in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Compute fib(40) recursively with a cache, and count how many times the function body actually runs compared with the plain recursive version for fib(25).

Solution
main.js
let plainCalls = 0;
function fibPlain(n) {
  plainCalls++;
  return n < 2 ? n : fibPlain(n - 1) + fibPlain(n - 2);
}

let memoCalls = 0;
const cache = new Map();
function fibMemo(n) {
  if (cache.has(n)) return cache.get(n);
  memoCalls++;
  const result = n < 2 ? n : fibMemo(n - 1) + fibMemo(n - 2);
  cache.set(n, result);
  return result;
}

console.log("fibPlain(25) =", fibPlain(25), "calls:", plainCalls);
console.log("fibMemo(25)  =", fibMemo(25), "calls:", memoCalls);
console.log("fibMemo(40)  =", fibMemo(40));

Output Verified by running it on Node.js

fibPlain(25) = 75025 calls: 242785
fibMemo(25)  = 75025 calls: 26
fibMemo(40)  = 102334155

The plain version recomputes the same values exponentially often (242,785 calls). With the cache each n is computed once, so fib(25) needs 26 calls and fib(40) is instant.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links