File tree Expand file tree Collapse file tree 1 file changed +11
-9
lines changed Expand file tree Collapse file tree 1 file changed +11
-9
lines changed Original file line number Diff line number Diff line change 7
7
* to avoid redundant calculations for improved efficiency.
8
8
*
9
9
* Example:
10
- * - Input: n = 5
11
- * - Output: 120
10
+ * Input: n = 5
11
+ * Output: 120
12
12
*
13
- * Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
13
+ * Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
14
14
*
15
- * - The program uses a recursive function fact_rec which caches computed
15
+ * The program uses a recursive function fact_recursion which caches computed
16
+ * results in a memo array to avoid recalculating factorials for the same numbers.
16
17
*
17
18
* Time Complexity: O(n)
18
19
* Space Complexity: O(n)
21
22
22
23
#include < iostream>
23
24
#include < cassert> // For test cases
24
- #include < cstdint>
25
- #include < array>
25
+ #include < array>
26
+ #include < cstdint> // For uint64_t
27
+
26
28
// / Array to store computed factorials for memoization
27
- std::array<__uint128_t , 1000 > memo{0 };
29
+ std::array<uint64_t , 1000 > memo{0 };
28
30
29
31
/* *
30
32
* @brief Computes the factorial of a non-negative integer using recursion and memoization.
31
33
* @param n The integer whose factorial is to be computed
32
34
* @returns The factorial of n
33
35
*/
34
- __uint128_t fact_recursion (__uint128_t n) {
36
+ uint64_t fact_recursion (uint64_t n) {
35
37
if (n == 0 ) return 1 ; // Base case: 0! = 1
36
38
if (memo[n] != 0 ) return memo[n]; // Return already computed value
37
39
memo[n] = n * fact_recursion (n - 1 ); // Store and return the computed value
38
40
return memo[n];
39
41
}
40
42
41
43
/* *
42
- * @brief Self-test implementations for the fact_rec function.
44
+ * @brief Self-test implementations for the fact_recursion function.
43
45
* @returns void
44
46
*/
45
47
void test_fact_recursion () {
You can’t perform that action at this time.
0 commit comments