Skip to content

Commit 031542b

Browse files
committed
✨ [1569] 100% memory beats - map caches factorial
1 parent 4ab4179 commit 031542b

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

1569/my_solution.js

+17-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
1-
const factorial = (n, sum = 1n) => {
2-
// console.log(`n:${n}, sum:${sum}`)
3-
if (0n === n) return sum;
4-
return factorial(n - 1n, sum * n)
1+
const cache = new Map();
2+
const factorial = (n) => {
3+
let sum = 1n;
4+
console.log(`n:${n}, sum:${sum}`)
5+
console.log("cache")
6+
console.log(cache)
7+
8+
if (cache.has(n)) return cache.get(n);
9+
let tmpN = n;
10+
while (n > 0n) {
11+
sum *= n;
12+
n--;
13+
}
14+
15+
cache.set(tmpN, sum);
16+
return sum;
17+
return factorial(n - 1n, sum * n);
518
}
619
// combination
720
const getCombination = (n, r) => {

1569/solution.js

+13-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1-
const factorial = (n, sum = 1n) => {
2-
if (0n === n) return sum;
3-
return factorial(n - 1n, sum * n)
1+
const cache = new Map();
2+
const factorial = (n) => {
3+
let sum = 1n;
4+
5+
if (cache.has(n)) return cache.get(n);
6+
let tmpN = n;
7+
while (n > 0n) {
8+
sum *= n;
9+
n--;
10+
}
11+
12+
cache.set(tmpN, sum);
13+
return sum;
414
}
515

616
const getCombination = (n, r) => {

0 commit comments

Comments
 (0)