Skip to content

Commit a7f6d25

Browse files
committed
Factorial space complexity
1 parent a60f486 commit a7f6d25

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

src/factorial/factorial.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
// Problem: return a factorial number of a given positive integer
22

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
46
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+
};
1113

1214
// Recursive approach:
15+
// Time complexity: O(n)
16+
// Space complexity: O(n)
1317
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+
};

0 commit comments

Comments
 (0)