TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
factorial_memoization.cpp
Go to the documentation of this file.
1
24
25#include <iostream> // for std::cout
26#include <cassert> // For test cases
27#include <array> // For std::array
28#include <cstdint> // For uint64_t
29
31std::array<uint64_t, 1000> memo{0};
32
37namespace math {
38
44uint64_t fact_recursion(uint64_t n) {
45 if (n == 0) return 1; // Base case: 0! = 1
46 if (memo[n] != 0) return memo[n]; // Return already computed value
47 memo[n] = n * fact_recursion(n - 1); // Store and return the computed value
48 return memo[n];
49}
50
51} // namespace math
57 // Test cases for factorial computation
58 assert(math::fact_recursion(0) == 1);
59 assert(math::fact_recursion(1) == 1);
60 assert(math::fact_recursion(5) == 120);
61 assert(math::fact_recursion(10) == 3628800);
62 std::cout << "All test cases passed!\n";
63}
64
69int main() {
70 // Run test cases
72 return 0;
73}
std::array< uint64_t, 1000 > memo
Array to store computed factorials for memoization.
void test_fact_recursion()
Self-test implementations for the fact_recursion function.
int main()
Main function to run test cases and interact with the user.
for assert
uint64_t fact_recursion(uint64_t n)
Computes the factorial of a non-negative integer using recursion and memoization.