Nth Fibonacci Number
Given a positive integer n, find the nth fibonacci number. Since the answer can be very large, return the answer modulo 1000000007.
Example 1:
Input: n = 2
Output: 1
Explanation: 1 is the 2nd number
of fibonacci series.
Example 2:
Input: n = 5
Output: 5
Explanation: 5 is the 5th number
of fibonacci series.
Your Task:
You dont need to read input or print anything. Complete the function nthFibonacci() which takes n as input parameter and returns nth fibonacci number.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1<= n <=1000
Solution :
We know that this can be solved using recursion and dp but what about the matrix. Lets start with a matrix [[a,b],[c,d]] and in the left we have [ f(n) , f(n-1) ] and in the right we have [[a,b],[c,d]] multiplied by [ f(n-1) , f(n-2) ]. We can find the value of a,b,c, and d by matching their coefficients. so now we can find the Fibonacci by just multiplying the matrix n times. Just like we make our own power function to reduce the time to calculate the power of big numbers we will here use exponentiation to calculate the power of a matrix.
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.