Created
June 9, 2020 21:46
-
-
Save nataliemarleny/d857bc4981da3097e8b83db79c05371f to your computer and use it in GitHub Desktop.
Memoization Example
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 fs = require("fs"); | |
// "4\n1\n2\n5\n3" | |
const input = fs.readFileSync(0).toString(); | |
// [4, 1, 2, 5, 3] | |
const lines = input.split("\n").map((n) => parseInt(n, 10)); | |
const T = parseInt(lines[0], 10); | |
// 2 | |
// 2 * 2 - 1 | |
// 5 | |
// 5 * 4 * 3 * 2 * 1 | |
// factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3)... | |
// factorial(N) = N * factorial(N - 1) | |
// factorial = 5 * factorial | |
// 5 * (5 - 1) * (5 - 2) * (5 - 3) * (5 - 4) | |
const memoize = {}; | |
const calcFactorial = (N) => { | |
if (N <= BigInt(1)) { | |
return BigInt(1); | |
} | |
if (memoize[N]) { | |
return memoize[N]; | |
} | |
const F = N * calcFactorial(N - BigInt(1)); | |
memoize[N] = F; | |
return F; | |
}; | |
for (let t = 1; t <= T; t += 1) { | |
const N = BigInt(lines[t]); | |
const factorial = calcFactorial(N); | |
console.log(`${factorial}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment