![]() |
TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Factorial calculation using recursion and memoization More...
#include <iostream>#include <cassert>#include <array>#include <cstdint>Go to the source code of this file.
Namespaces | |
| namespace | math |
| for assert | |
Functions | |
| uint64_t | math::fact_recursion (uint64_t n) |
| Computes the factorial of a non-negative integer using recursion and 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. | |
Variables | |
| std::array< uint64_t, 1000 > | memo {0} |
| Array to store computed factorials for memoization. | |
Factorial calculation using recursion and memoization
This program computes the factorial of a non-negative integer using recursion with memoization (top-down dynamic programming). It stores intermediate results to avoid redundant calculations for improved efficiency.
Memoization is a form of caching where the result to an expensive function call is stored and returned. Example: Input: n = 5 Output: 120
Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120
The program uses a recursive function fact_recursion which caches computed results in a memo array to avoid recalculating factorials for the same numbers.
Time Complexity: O(n) Space Complexity: O(n)
Definition in file factorial_memoization.cpp.
| int main | ( | void | ) |
Main function to run test cases and interact with the user.
Definition at line 69 of file factorial_memoization.cpp.
| void test_fact_recursion | ( | ) |
Self-test implementations for the fact_recursion function.
Definition at line 56 of file factorial_memoization.cpp.
| std::array<uint64_t, 1000> memo {0} |
Array to store computed factorials for memoization.
Definition at line 31 of file factorial_memoization.cpp.