Last active
November 30, 2017 21:04
-
-
Save nonlogos/d6803e4de4bcd56b1e90c172262bb996 to your computer and use it in GitHub Desktop.
fibonacci with memoisation
This file contains hidden or 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
// 5 * 4 * 3 * 2 * 1 | |
const factorial = (n) => { | |
//base case | |
if (n === 1) return 1; | |
// logic | |
return n * factorial(n-1); | |
} | |
console.log(factorial(5)) |
This file contains hidden or 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 fib = (n, mem) => { | |
// memoise | |
mem = mem || {}; | |
//base case | |
if (n <= 1) return 1; | |
if (mem[n]) return mem[n]; | |
return mem[n] = fib(n-1, mem) + fib(n-2, mem); | |
} | |
console.log(fib(5)) // return 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment