TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fibonacci_sum.cpp
Go to the documentation of this file.
1
15#include <cassert>
16#include <cstdint>
17#include <iostream>
18#include <vector>
19
24namespace math {
30namespace fibonacci_sum {
31using matrix = std::vector<std::vector<uint64_t> >;
32
39math::fibonacci_sum::matrix multiply(const math::fibonacci_sum::matrix &T,
40 const math::fibonacci_sum::matrix &A) {
41 math::fibonacci_sum::matrix result(2, std::vector<uint64_t>(2, 0));
42
43 // multiplying matrices
44 result[0][0] = T[0][0] * A[0][0] + T[0][1] * A[1][0];
45 result[0][1] = T[0][0] * A[0][1] + T[0][1] * A[1][1];
46 result[1][0] = T[1][0] * A[0][0] + T[1][1] * A[1][0];
47 result[1][1] = T[1][0] * A[0][1] + T[1][1] * A[1][1];
48
49 return result;
50}
51
58math::fibonacci_sum::matrix power(math::fibonacci_sum::matrix T, uint64_t ex) {
59 math::fibonacci_sum::matrix A{{1, 1}, {1, 0}};
60 if (ex == 0 || ex == 1) {
61 return T;
62 }
63
64 T = power(T, ex / 2);
65 T = multiply(T, T);
66 if (ex & 1) {
67 T = multiply(T, A);
68 }
69 return T;
70}
71
77uint64_t result(uint64_t n) {
78 math::fibonacci_sum::matrix T{{1, 1}, {1, 0}};
79 T = power(T, n);
80 uint64_t ans = T[0][1];
81 ans = (ans - 1);
82 return ans;
83}
84
91uint64_t fiboSum(uint64_t n, uint64_t m) {
92 return (result(m + 2) - result(n + 1));
93}
94} // namespace fibonacci_sum
95} // namespace math
96
102static void test() {
103 uint64_t n = 0, m = 3;
104 uint64_t test_1 = math::fibonacci_sum::fiboSum(n, m);
105 assert(test_1 == 4);
106 std::cout << "Passed Test 1!" << std::endl;
107
108 n = 3;
109 m = 5;
110 uint64_t test_2 = math::fibonacci_sum::fiboSum(n, m);
111 assert(test_2 == 10);
112 std::cout << "Passed Test 2!" << std::endl;
113
114 n = 5;
115 m = 7;
116 uint64_t test_3 = math::fibonacci_sum::fiboSum(n, m);
117 assert(test_3 == 26);
118 std::cout << "Passed Test 3!" << std::endl;
119
120 n = 7;
121 m = 10;
122 uint64_t test_4 = math::fibonacci_sum::fiboSum(n, m);
123 assert(test_4 == 123);
124 std::cout << "Passed Test 4!" << std::endl;
125
126 n = 9;
127 m = 12;
128 uint64_t test_5 = math::fibonacci_sum::fiboSum(n, m);
129 assert(test_5 == 322);
130 std::cout << "Passed Test 5!" << std::endl;
131}
132
137int main() {
138 test(); // execute the tests
139 return 0;
140}
uint64_t fiboSum(uint64_t n, uint64_t m)
math::fibonacci_sum::matrix power(math::fibonacci_sum::matrix T, uint64_t ex)
static void test()
uint64_t result(uint64_t n)
int main()
Main function.
static void test_1()
static void test_2()
static void test_3()
std::vector< std::valarray< T > > matrix
Functions for the sum of the Fibonacci Sequence: .
for assert