File tree Expand file tree Collapse file tree 1 file changed +17
-13
lines changed Expand file tree Collapse file tree 1 file changed +17
-13
lines changed Original file line number Diff line number Diff line change 1
1
// Problem: return a factorial number of a given positive integer
2
2
3
- // Loop approach:
3
+ // Loop approach:
4
+ // Time complexity: O(n) - no new values are created, values only change with each loop
5
+ // Space complexity: O(1) - space occupied in the memory does not depend on the number
4
6
export const getFactorial = ( num ) => {
5
- let result = 1
6
- for ( let i = 2 ; i <= num ; i ++ ) {
7
- result *= i
8
- }
9
- return result
10
- }
7
+ let result = 1 ;
8
+ for ( let i = 2 ; i <= num ; i ++ ) {
9
+ result *= i ;
10
+ }
11
+ return result ;
12
+ } ;
11
13
12
14
// Recursive approach:
15
+ // Time complexity: O(n)
16
+ // Space complexity: O(n)
13
17
export const getFactorialRecursion = ( num ) => {
14
- if ( num > 1 ) {
15
- return num * getFactorialRecursion ( num - 1 )
16
- } else {
17
- return 1
18
- }
19
- }
18
+ if ( num > 1 ) {
19
+ return num * getFactorialRecursion ( num - 1 ) ;
20
+ } else {
21
+ return 1 ;
22
+ }
23
+ } ;
You can’t perform that action at this time.
0 commit comments