File tree 2 files changed +30
-7
lines changed
2 files changed +30
-7
lines changed Original file line number Diff line number Diff line change 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 ) ;
5
18
}
6
19
// combination
7
20
const getCombination = ( n , r ) => {
Original file line number Diff line number Diff line change 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 ;
4
14
}
5
15
6
16
const getCombination = ( n , r ) => {
You can’t perform that action at this time.
0 commit comments