TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
factorial_memoization.cpp File Reference

Factorial calculation using recursion and memoization More...

#include <iostream>
#include <cassert>
#include <array>
#include <cstdint>
Include dependency graph for factorial_memoization.cpp:

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.

Detailed Description

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)

Author
Vedant Mukhedkar

Definition in file factorial_memoization.cpp.

Function Documentation

◆ main()

int main ( void )

Main function to run test cases and interact with the user.

Returns
0 on program success

Definition at line 69 of file factorial_memoization.cpp.

69 {
70 // Run test cases
72 return 0;
73}
void test_fact_recursion()
Self-test implementations for the fact_recursion function.

◆ test_fact_recursion()

void test_fact_recursion ( )

Self-test implementations for the fact_recursion function.

Returns
void

Definition at line 56 of file factorial_memoization.cpp.

56 {
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}
uint64_t fact_recursion(uint64_t n)
Computes the factorial of a non-negative integer using recursion and memoization.

Variable Documentation

◆ memo

std::array<uint64_t, 1000> memo {0}

Array to store computed factorials for memoization.

Definition at line 31 of file factorial_memoization.cpp.

31{0};