6
6
* with memoization (top-down dynamic programming). It stores intermediate results
7
7
* to avoid redundant calculations for improved efficiency.
8
8
*
9
+ * Example:
10
+ * - Input: n = 5
11
+ * - Output: 120
12
+ *
13
+ * Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
14
+ *
15
+ * - The program uses a recursive function fact_rec which caches computed
16
+ *
9
17
* Time Complexity: O(n)
10
18
* Space Complexity: O(n)
11
19
* @author [Vedant Mukhedkar](https://github.com/git5v)
@@ -22,23 +30,23 @@ std::array<__uint128_t, 1000> memo{0};
22
30
* @param n The integer whose factorial is to be computed
23
31
* @returns The factorial of n
24
32
*/
25
- __uint128_t fact_rec (__uint128_t n) {
33
+ __uint128_t fact_recursion (__uint128_t n) {
26
34
if (n == 0 ) return 1 ; // Base case: 0! = 1
27
35
if (memo[n] != 0 ) return memo[n]; // Return already computed value
28
- memo[n] = n * fact_rec (n - 1 ); // Store and return the computed value
36
+ memo[n] = n * fact_recursion (n - 1 ); // Store and return the computed value
29
37
return memo[n];
30
38
}
31
39
32
40
/* *
33
41
* @brief Self-test implementations for the fact_rec function.
34
42
* @returns void
35
43
*/
36
- void test_fact_rec () {
44
+ void test_fact_recursion () {
37
45
// Test cases for factorial computation
38
- assert (fact_rec (0 ) == 1 );
39
- assert (fact_rec (1 ) == 1 );
40
- assert (fact_rec (5 ) == 120 );
41
- assert (fact_rec (10 ) == 3628800 );
46
+ assert (fact_recursion (0 ) == 1 );
47
+ assert (fact_recursion (1 ) == 1 );
48
+ assert (fact_recursion (5 ) == 120 );
49
+ assert (fact_recursion (10 ) == 3628800 );
42
50
std::cout << " All test cases passed!\n " ;
43
51
}
44
52
@@ -48,6 +56,6 @@ void test_fact_rec() {
48
56
*/
49
57
int main () {
50
58
// Run test cases
51
- test_fact_rec ();
59
+ test_fact_recursion ();
52
60
return 0 ;
53
61
}
0 commit comments