forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
30 lines (28 loc) · 722 Bytes
/
Copy pathindex.js
File metadata and controls
30 lines (28 loc) · 722 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
* @param {Number} n
* @return {Number}
*/
const factorialRecursive = (n) => {
if (n < 0) throw new Error('Factorial of negative numbers isn\'t defined');
else if (n == 0) return 1;
else if (n == 1) return 1;
return n * factorialRecursive(n-1);
};
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
* @param {Number} n
* @return {Number}
*/
const factorialIterative = (n) => {
if (n < 0) throw new Error('Factorial of negative numbers isn\'t defined');
else if (n == 0) return 1;
let finalValue = n;
for (let i = 2; i< n; i += 1) {
finalValue *= i;
}
return finalValue;
};
module.exports = {factorialIterative, factorialRecursive};