You want to get tutelage under the Ultimate Ninja Ankush, but for that you have to pass his test. His test is simple: he has given you a relation function, F(n) = 2*F(n-1) + 3*F(n-2),where F(0) = F(1) = 1 and wants you to find the ‘N’th term for the function.
The 'N'th term can be very large, return it after modulus 10^9 + 7.
For example:
Given ‘N’ = 3,
F(3) = 13,This is because F(0) = 1, F(1) = 1, Therefore F(2) = 2*F(1) + 3*F(1), therefore F(2) = 5, and F(3) = 2*F(2) + 3*F(1), therefore F(3) = 13.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines contains a single integer ‘N’, which denotes the number given to us.
Output Format :
For each test case, You are supposed to return the Nth term for the given relation.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10 ^ 9
Time Limit: 1sec.
2
3
4
13
41
In the first test case,F(3) = 13,This is because F(0) = 1, F(1) = 1, Therefore F(2) = 2*F(1) + 3*F(1), therefore F(2) = 5, and F(3) = 2*F(2) + 3*F(1), therefore F(3) = 13.
In the second test case, F(4) = 41, This is because F(2) = 5, F(3) = 13, F(4) = 2*F(3) + 3*F(2), therefore F(4) = 41.
2
5
2
121
5
Can this be found recursively?
The idea is to recur according to the given relation i.e. F(N) = 2*F(N - 1) + 3*F(N - 2).
The steps are as follows:
O(2 ^ N), Where ‘N’ is the number given to us.
Since we are recurring 2 times for each ‘N’, the overall time complexity will be O(2 ^ N).
O(N), Where ‘N’ is the number given to us.
Since we are recurring 2 times for each ‘N’, therefore, the overall space complexity is O(N).