-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalg_factorial.cc
75 lines (59 loc) · 1.43 KB
/
alg_factorial.cc
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
// Factorial by recursion.
// Time complexity: O(n).
// Space complexity: O(n).
int FactorialRecur(int n) {
if (n <= 1)
return 1;
return n * FactorialRecur(n - 1);
}
// Helper function for FactorialMemo().
int FactorialMemoUtil(int n, std::vector<int>& T) {
if (T[n] > 0)
return T[n];
if (n <= 1)
return 1;
T[n] = n * FactorialMemoUtil(n - 1, T);
return T[n];
}
// Factorial by top-down recursion w/ memoization.
// Time complexity: O(n).
// Space complexity: O(n).
int FactorialMemo(int n) {
std::vector<int> T(n + 1, 0);
T[0] = 1;
T[1] = 1;
return FactorialMemoUtil(n, T);
}
// Factorial by bottom-up dynamic programming.
// Time complexity: O(n).
// Space complexity: O(n).
int FactorialDp(int n) {
std::vector<int> T(n + 1, 0);
T[0] = 1;
T[1] = 1;
for (int i = 2; i <= n; i++)
T[i] = i * T[i - 1];
return T[n];
}
// Factorial by bottom-up dynamic programming w/ optimized space.
// Time complexity: O(n).
// Space complexity: O(1).
int FactorialIter(int n) {
int fact = 1;
if (n <= 1)
return fact;
else
for (int i = 2; i <= n; i++)
fact = i * fact;
return fact;
}
int main() {
int n = 5;
std::cout << "Recur: " << FactorialRecur(n) << std::endl;
std::cout << "Memo: " << FactorialMemo(n) << std::endl;
std::cout << "DP: " << FactorialDp(n) << std::endl;
std::cout << "Iter: " << FactorialIter(n) << std::endl;
return 0;
}