Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added recursion (fib) with caching #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

TheWebDevel
Copy link

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));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant