Skip to content

Commit 30d49e3

Browse files
authored
Update factorial_memoization.cpp
1 parent 413e2d9 commit 30d49e3

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

math/factorial_memoization.cpp

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66
* with memoization (top-down dynamic programming). It stores intermediate results
77
* to avoid redundant calculations for improved efficiency.
88
*
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+
*
917
* Time Complexity: O(n)
1018
* Space Complexity: O(n)
1119
* @author [Vedant Mukhedkar](https://github.com/git5v)
@@ -22,23 +30,23 @@ std::array<__uint128_t, 1000> memo{0};
2230
* @param n The integer whose factorial is to be computed
2331
* @returns The factorial of n
2432
*/
25-
__uint128_t fact_rec(__uint128_t n) {
33+
__uint128_t fact_recursion(__uint128_t n) {
2634
if (n == 0) return 1; // Base case: 0! = 1
2735
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
2937
return memo[n];
3038
}
3139

3240
/**
3341
* @brief Self-test implementations for the fact_rec function.
3442
* @returns void
3543
*/
36-
void test_fact_rec() {
44+
void test_fact_recursion() {
3745
// 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);
4250
std::cout << "All test cases passed!\n";
4351
}
4452

@@ -48,6 +56,6 @@ void test_fact_rec() {
4856
*/
4957
int main() {
5058
// Run test cases
51-
test_fact_rec();
59+
test_fact_recursion();
5260
return 0;
5361
}

0 commit comments

Comments
 (0)