TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
catalan_numbers.cpp
Go to the documentation of this file.
1
12#include <cassert>
13#include <cstdint>
14#include <cstdlib>
15#include <functional>
16#include <numeric>
17#include <vector>
18
23 using value_type = std::uint64_t;
24 std::vector<value_type> known{1, 1};
25
26 value_type compute_next() {
27 return std::transform_reduce(known.begin(), known.end(), known.rbegin(),
28 static_cast<value_type>(0), std::plus<>(),
29 std::multiplies<>());
30 }
31
32 void add() { known.push_back(this->compute_next()); }
33
34 public:
39 value_type get(std::size_t n) {
40 while (known.size() <= n) {
41 this->add();
42 }
43 return known[n];
44 }
45};
46
47void test_catalan_numbers_up_to_20() {
48 // data verified with https://oeis.org/A000108/
50 assert(cn.get(0) == 1ULL);
51 assert(cn.get(1) == 1ULL);
52 assert(cn.get(2) == 2ULL);
53 assert(cn.get(3) == 5ULL);
54 assert(cn.get(4) == 14ULL);
55 assert(cn.get(5) == 42ULL);
56 assert(cn.get(6) == 132ULL);
57 assert(cn.get(7) == 429ULL);
58 assert(cn.get(8) == 1430ULL);
59 assert(cn.get(9) == 4862ULL);
60 assert(cn.get(10) == 16796ULL);
61 assert(cn.get(11) == 58786ULL);
62 assert(cn.get(12) == 208012ULL);
63 assert(cn.get(13) == 742900ULL);
64 assert(cn.get(14) == 2674440ULL);
65 assert(cn.get(15) == 9694845ULL);
66 assert(cn.get(16) == 35357670ULL);
67 assert(cn.get(17) == 129644790ULL);
68 assert(cn.get(18) == 477638700ULL);
69 assert(cn.get(19) == 1767263190ULL);
70 assert(cn.get(20) == 6564120420ULL);
71}
72
73void test_catalan_numbers_25() {
74 // data verified with https://oeis.org/A000108/
76 assert(cn.get(25) == 4861946401452ULL);
77}
78
79int main() {
80 test_catalan_numbers_up_to_20();
81 test_catalan_numbers_25();
82}
computes and caches Catalan numbers
value_type get(std::size_t n)
computes the n-th Catalan number and updates the cache.
int main()
Main function.