Find Nth term (A matrix exponentiation example)
We are given a recursive function that describes Nth terms in the form of other terms. In this article, we have taken specific examples.
Now you are given n, and you have to find out nth term using the above formula.
Input : n = 2 Output : 5 Input : n = 3 Output :13
Basic Approach: This problem can be solved by simply just iterating over the n terms. Every time you find a term, using this term find the next one, and so on. But the time complexity of this problem is of order O(n).
All such problems where a term is a function of other terms in a linear fashion. Then these can be solved using the Matrix (Please refer: Matrix Exponentiation ). First, we make a transformation matrix and then just use matrix exponentiation to find the Nth term.
Step by Step method includes:
- Step 1. Determine k the number of terms on which T(i) depends.
For our example, T(i) depends on two terms. So, k = 2
- Step 2. Determine initial values
As in this article T0=1, T1=1 are given.
- Step 3. Determine TM, the transformation matrix.
This is the most important step in solving recurrence relations. In this step, we have to make the matrix of dimension k*k.
T(i)=TM*(initial value vector)
Here initial value vector is the vector that contains an initial value. We name this vector as initial.
Below is the program to implement the above approach.
Time Complexity : O(Log n)
Auxiliary Space: O(m2), where m is the order of the transformation matrix. Here, m is 2.
The same idea is used to find n-th Fibonacci number in O(Log n)
Please Login to comment...