N-th Fibonacci Number

Moderate
0/80
Average time to solve is 40m
profile
Contributed by
730 upvotes
Asked in companies
AmazonWalmartTata Consultancy Services (TCS)

Problem statement

You are given an integer ‘N’, your task is to find and return the N’th Fibonacci number using matrix exponentiation.

Since the answer can be very large, return the answer modulo 10^9 +7.

Fibonacci number is calculated using the following formula:
F(n) = F(n-1) + F(n-2), 
Where, F(1) = F(2) = 1.
For Example:
For ‘N’ = 5, the output will be 5.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.

The first line of each test case contains a single integer ‘N’, representing the integer for which we have to find its equivalent Fibonacci number.
Output Format:
For each test case, print a single integer representing the N’th Fibonacci number.

Return answer modulo 10^9 + 7.

Output for each test case will be printed in a separate line.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5

Time Limit: 1 sec.
Sample Input 1:
2
10
7
Sample Output 1:
55
13
Explanation For Sample Output 1:
For the first test case, the 10th Fibonacci number is 55.
For the second test case, the 7th Fibonacci number is 13.
Sample Input 2:
2
1
3
Sample Output 2:
1
2
Hint

What is recursion?

Approaches (4)
Recursive Approach (TLE)
  • In this approach, we use recursion and uses a basic condition that :
    • If ‘N’ is smaller than ‘1’(N<=1) we return ‘N’
    • Else we call the function again as ninjaJasoos(N-1) + ninjaJasoos(N-2).
  • In this way, we reached our answer.
Time Complexity

O(2^N), where ‘N’ is the number for which we are finding its equivalent Fibonacci.

 

As our function will be called exponentially.

Space Complexity

O(N),  where ‘N’ is the given number.  
 

As recursion uses a stack of size ‘N’

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
N-th Fibonacci Number
Full screen
Console