TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Matrix Exponentiation. More...
#include <iostream>
#include <vector>
Go to the source code of this file.
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.
Definition in file matrix_exponentiation.cpp.
#define endl std::endl |
shorthand definition for std::endl
Definition at line 36 of file matrix_exponentiation.cpp.
#define ll int64_t |
shorthand definition for int64_t
Definition at line 33 of file matrix_exponentiation.cpp.
#define MOD 1000000007 |
Definition at line 40 of file matrix_exponentiation.cpp.
#define pb push_back |
shorthand definition for int64_t
Definition at line 39 of file matrix_exponentiation.cpp.
Wrapper for Fibonacci
[in] | n | \(n^\text{th}\) Fibonacci number |
Definition at line 91 of file matrix_exponentiation.cpp.
int main | ( | void | ) |
Main function
Definition at line 126 of file matrix_exponentiation.cpp.
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) |
Definition at line 57 of file matrix_exponentiation.cpp.
computing integer power of a matrix using recursive multiplication.
[in] | A | base matrix |
[in] | p | exponent |
Definition at line 76 of file matrix_exponentiation.cpp.
vector<ll> fib_b |
global vector variables used in the ans function.
Definition at line 50 of file matrix_exponentiation.cpp.
vector<ll> fib_c |
Definition at line 50 of file matrix_exponentiation.cpp.
ll mat_size |
global variable mat_size
Definition at line 45 of file matrix_exponentiation.cpp.