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
22
23#include <cassert> // For test cases
24#include <cstdint> // For uint64_t
25#include <vector> // For std::vector
26
28 std::vector<std::uint64_t> known_values = {1};
29
30 public:
36 std::uint64_t operator()(std::uint64_t n) {
37 if (n >= this->known_values.size()) {
38 this->known_values.push_back(n * this->operator()(n - 1));
39 }
40 return this->known_values.at(n);
41 }
42};
43
44void test_MemorisedFactorial_in_order() {
46 assert(factorial(0) == 1);
47 assert(factorial(1) == 1);
48 assert(factorial(5) == 120);
49 assert(factorial(10) == 3628800);
50}
51
52void test_MemorisedFactorial_no_order() {
54 assert(factorial(10) == 3628800);
55}
56
61int main() {
62 test_MemorisedFactorial_in_order();
63 test_MemorisedFactorial_no_order();
64 return 0;
65}
std::uint64_t operator()(std::uint64_t n)
int main()
Main function to run tests.
uint64_t factorial(uint8_t n)
function to find factorial of given number
Definition factorial.cpp:29