Skip to content

Instantly share code, notes, and snippets.

@nataliemarleny
Created June 9, 2020 21:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nataliemarleny/d857bc4981da3097e8b83db79c05371f to your computer and use it in GitHub Desktop.
Save nataliemarleny/d857bc4981da3097e8b83db79c05371f to your computer and use it in GitHub Desktop.
Memoization Example
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