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));
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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!