Skip to content

Commit 030c69c

Browse files
authored
Create factorial_top_down_dp.cpp
1 parent 13d062d commit 030c69c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* @file
3+
* @brief [Factorial calculation using recursion and memoization (dynamic programming)](https://en.wikipedia.org/wiki/Factorial)
4+
* @details
5+
* This program computes the factorial of a non-negative integer using recursion
6+
* with memoization (top-down dynamic programming). It stores intermediate results
7+
* to avoid redundant calculations for improved efficiency.
8+
*
9+
* Time Complexity: O(n)
10+
* Space Complexity: O(n)
11+
@author [Vedant Mukhedkar](https://github.com/git5v)
12+
*/
13+
14+
#include <iostream>
15+
#include <cassert> // For test cases
16+
17+
/// Array to store computed factorials for memoization
18+
long long memo[1000] = {0};
19+
20+
/**
21+
* @brief Computes the factorial of a non-negative integer using recursion and memoization.
22+
* @param n The integer whose factorial is to be computed
23+
* @returns The factorial of n
24+
*/
25+
long long fact_rec(int n) {
26+
if (n == 0) return 1; // Base case: 0! = 1
27+
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
29+
return memo[n];
30+
}
31+
32+
/**
33+
* @brief Self-test implementations for the fact_rec function.
34+
* @returns void
35+
*/
36+
void test_fact_rec() {
37+
// 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);
42+
std::cout << "All test cases passed!\n";
43+
}
44+
45+
/**
46+
* @brief Main function to run test cases and interact with the user.
47+
* @returns 0 on program success
48+
*/
49+
int main() {
50+
// Run test cases
51+
test_fact_rec();
52+
53+
// User interaction loop
54+
// int n;
55+
// std::cout << "Enter a non-negative integer to compute factorial (0 to exit): ";
56+
// std::cin >> n;
57+
// if (n < 0) {
58+
// std::cout << "Please enter a non-negative integer only.\n";
59+
// return 0;
60+
// }
61+
// std::cout << "Factorial of " << n << " = " << fact_rec(n) << std::endl;
62+
63+
return 0;
64+
}

0 commit comments

Comments
 (0)