Skip to content

Instantly share code, notes, and snippets.

@dan1elhughes
Last active August 9, 2018 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan1elhughes/0b8fbb21e9df988dae802a2b8edb190f to your computer and use it in GitHub Desktop.
Save dan1elhughes/0b8fbb21e9df988dae802a2b8edb190f to your computer and use it in GitHub Desktop.
const assert = require('assert');
const naiveFib = n => {
if (n === 1 || n === 2) return 1;
return naiveFib(n - 1) + naiveFib(n - 2);
};
console.time("naive");
assert(naiveFib(45) === 1134903170);
console.timeEnd("naive");
// => 9757.694ms
const memoFib = (n, memo = [0, 1, 1]) => {
if (!memo[n]) {
memo[n] = memoFib(n - 1, memo) + memoFib(n - 2, memo);
}
return memo[n];
};
console.time("memo");
assert(memoFib(45) === 1134903170);
console.timeEnd("memo");
// => 0.057ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment