First and foremost, it is highly recommended to go through Binary Exponentiation, if you are not acquainted with it or don't remember it clearly. It is expected that reader knows Multiplication of two matrices.
Matrix exponentiation is all about finding a matrix T such that T⋅A=B where A and B are two matrices of appropriate order. Before we delve deeper let's us recall two things:
Matrix Multiplication is associativei.e., A⋅(B⋅C)=(A⋅B)⋅C
A matrix A of order (n×m) can be multiplied with another matrix of order (m×p)only.
Q.1. Before we go any further, let us solve a problem. Find a matrix T such that T⋅A = B, where
A=abc;B=[2a+3ba+2b+4c] Answer
T=[213202]
Verify the following yourself:
[213202]⋅abc=[2a+3ba+2b+4c]
If you are struggling with matrix multiplication remember that Bi,j comes from sum and product of ithrow of A and jthcolumn of B.
Q.2. Find a matrix T such that T⋅A=B, where
A=abcB=a+3b2b+3c5a+3b+7c6a Answer
T=105632300370
Verify it yourself!
Let us now see a concrete problem that can be solved using Matrix Exponentiation.
We can solve the problem using top-down dynamic programming or by bottom-up dynamic programming, but let us see how we can solve it using Matrix Exponentiation first. The recurrence for fibonacci series is:
T⋅(T⋅[f(1)f(0)])=[f(3)f(2)]⟹(T⋅T)⋅[f(1)f(0)]=[f(3)f(2)](∵ Matrix multiplication is associative.)⟹T2⋅[f(1)f(0)]=[f(3)f(2)]=[f(1+2)f(0+2)]
From above pattern, we can conclude that,
(T)n⋅[f(1)f(0)]=[f(1+n)f(0+n)]
But this solution is not better than dynamic programming solution which runs in O(n) time, infact our matrix exponentiation runs in O(n⋅23) time. The extra factor of 23 comes from matrix multiplication (Matrix multiplication of two (n×n) matrix takes O(n3) time). To optimise our solution further we can use binary exponentiation to calculate Tn in O(log(n)⋅k3) time, where k is the dimension of matrix. In this case k=2.
Let us see the code for the above idea. Our code can be divided into three broad functions: