|
Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
|
Matrix Exponentiation. More...
#include <iostream>#include <vector>Macros | |
| #define | ll int64_t |
| #define | endl std::endl |
| #define | pb push_back |
| #define | MOD 1000000007 |
Functions | |
| vector< vector< ll > > | multiply (const vector< vector< ll > > &A, const vector< vector< ll > > &B) |
| vector< vector< ll > > | power (const vector< vector< ll > > &A, ll p) |
| ll | ans (ll n) |
| int | main () |
Variables | |
| ll | mat_size |
| vector< ll > | fib_b |
| vector< ll > | fib_c |
Matrix Exponentiation.
The problem can be solved with DP but constraints are high.
\(a_i = b_i\) (for \(i <= k\))
\(a_i = c_1 a_{i-1} + c_2 a_{i-2} + ... + c_k a_{i-k}\) (for \(i > k\))
Taking the example of Fibonacci series, \(k=2\)
\(b_1 = 1,\; b_2=1\)
\(c_1 = 1,\; c_2=1\)
\(a = \begin{bmatrix}0& 1& 1& 2& \ldots\end{bmatrix}\)
This way you can find the \(10^{18}\) fibonacci numberMOD. I have given a general way to use it. The program takes the input of B and C matrix.
Steps for Matrix Expo
The first element of this matrix is the required result.
| #define endl std::endl |
shorthand definition for std::endl
| #define ll int64_t |
shorthand definition for int64_t
| #define pb push_back |
shorthand definition for int64_t
Wrapper for Fibonacci
| [in] | n | \(n^\text{th}\) Fibonacci number |
| int main | ( | void | ) |
| vector< vector< ll > > multiply | ( | const vector< vector< ll > > & | A, |
| const vector< vector< ll > > & | B | ||
| ) |
To multiply 2 matrices
| [in] | A | matrix 1 of size (m \(\times\)n) |
| [in] | B | matrix 2 of size (p \(\times\)q) |
computing integer power of a matrix using recursive multiplication.
| [in] | A | base matrix |
| [in] | p | exponent |