Last active
August 9, 2018 10:37
-
-
Save dan1elhughes/0b8fbb21e9df988dae802a2b8edb190f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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