Skip to content

Commit fb3f95e

Browse files
authored
Update factorial_memoization.cpp
added cstdint header and switched to uint64 Thanks
1 parent 79e0ba9 commit fb3f95e

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

math/factorial_memoization.cpp

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@
77
* to avoid redundant calculations for improved efficiency.
88
*
99
* Example:
10-
* - Input: n = 5
11-
* - Output: 120
10+
* Input: n = 5
11+
* Output: 120
1212
*
13-
* Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
13+
* Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
1414
*
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.
1617
*
1718
* Time Complexity: O(n)
1819
* Space Complexity: O(n)
@@ -21,25 +22,26 @@
2122

2223
#include <iostream>
2324
#include <cassert> // For test cases
24-
#include <cstdint>
25-
#include <array>
25+
#include <array>
26+
#include <cstdint> // For uint64_t
27+
2628
/// Array to store computed factorials for memoization
27-
std::array<__uint128_t, 1000> memo{0};
29+
std::array<uint64_t, 1000> memo{0};
2830

2931
/**
3032
* @brief Computes the factorial of a non-negative integer using recursion and memoization.
3133
* @param n The integer whose factorial is to be computed
3234
* @returns The factorial of n
3335
*/
34-
__uint128_t fact_recursion(__uint128_t n) {
36+
uint64_t fact_recursion(uint64_t n) {
3537
if (n == 0) return 1; // Base case: 0! = 1
3638
if (memo[n] != 0) return memo[n]; // Return already computed value
3739
memo[n] = n * fact_recursion(n - 1); // Store and return the computed value
3840
return memo[n];
3941
}
4042

4143
/**
42-
* @brief Self-test implementations for the fact_rec function.
44+
* @brief Self-test implementations for the fact_recursion function.
4345
* @returns void
4446
*/
4547
void test_fact_recursion() {

0 commit comments

Comments
 (0)