TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
n_bonacci.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <cstdint>
20#include <iostream>
21#include <vector>
26namespace math {
32namespace n_bonacci {
40std::vector<uint64_t> N_bonacci(const uint64_t &n, const uint64_t &m) {
41 std::vector<uint64_t> a(
42 m, 0); // we create an array of size m filled with zeros
43 if (m < n || n == 0) {
44 return a;
45 }
46
47 a[n - 1] = 1;
49 if (n == m) {
50 return a;
51 }
52 a[n] = 1;
54 for (uint64_t i = n + 1; i < m; i++) {
55 // this is an optimized solution that works in O(M) time and takes O(M)
56 // extra space here we use the concept of the sliding window the current
57 // term can be computed using the given formula
58 a[i] = 2 * a[i - 1] - a[i - 1 - n];
59 }
60 return a;
61}
62} // namespace n_bonacci
63} // namespace math
64
69static void test() {
70 struct TestCase {
71 const uint64_t n;
72 const uint64_t m;
73 const std::vector<uint64_t> expected;
74 TestCase(const uint64_t in_n, const uint64_t in_m,
75 std::initializer_list<uint64_t> data)
76 : n(in_n), m(in_m), expected(data) {
77 assert(data.size() == m);
78 }
79 };
80 const std::vector<TestCase> test_cases = {
81 TestCase(0, 0, {}),
82 TestCase(0, 1, {0}),
83 TestCase(0, 2, {0, 0}),
84 TestCase(1, 0, {}),
85 TestCase(1, 1, {1}),
86 TestCase(1, 2, {1, 1}),
87 TestCase(1, 3, {1, 1, 1}),
88 TestCase(5, 15, {0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464}),
90 6, 17,
91 {0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976}),
92 TestCase(56, 15, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})};
93
94 for (const auto &tc : test_cases) {
95 assert(math::n_bonacci::N_bonacci(tc.n, tc.m) == tc.expected);
96 }
97 std::cout << "passed" << std::endl;
98}
99
104int main() {
105 test(); // run self-test implementations
106 return 0;
107}
int data[MAX]
test data
std::vector< uint64_t > N_bonacci(const uint64_t &n, const uint64_t &m)
Finds the N-Bonacci series for the n parameter value and m parameter terms.
Definition n_bonacci.cpp:40
static void test()
Self-test implementations.
Definition n_bonacci.cpp:69
int main()
Main function.
for assert
Functions for the N-bonacci implementation.
represents single example inputs and expected output of the function longest_common_string_length