You are given an integer ‘N’. Your task is to find out the ‘N’th Tribonacci Number. ‘N’th number in the Tribonacci sequence is defined as Tn = T n - 1 + Tn - 2 + Tn - 3. Where T0 = 0, T1 = 1, T2= 1. Return the answer in mod of 109 + 7.
For Example :You are given ‘N’ = 5, Here we know 0th, 1st and 2nd Tribonacci numbers are 0, 1 and 1 respectively. Therefore we can calculate the 3rd number as 0 + 1 + 1 = 2 and 4th number as 1 + 1 + 2 = 4 and 5th number as 1 + 2 + 4 = 7. Hence the answer is 7.
Follow Up :
Can you solve it in logarithmic time?
The first input line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing Tribonacci number to find.
Output Format :
For each test case, print a single integer, representing the ‘N’th Tribonacci Number.
Print a separate line for each test case.
1 ≤ T ≤10
0 ≤ N ≤ 10^5
Time Limit: 1 sec
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
2
5
2
7
1
For the first test case, ‘N’ = 5, Here we know 0th, 1st and 2nd Tribonacci numbers are 0, 1 and 1 respectively. Therefore we can calculate the 3rd number as 0 + 1 + 1 = 2 and 4th number as 1 + 1 + 2 = 4 and 5th number as 1 + 2 + 4 = 7. Hence the answer is 7.
For the second test case, ‘N’ = 2, Here, the second number in the Tribonacci sequence is already defined as 1. Hence the answer is 1.
2
0
9
0
81
Try to solve it in a brute force manner.
In this approach, we will make the function recursive, since and then add the base cases the Tribonacci sequence that is given in the question.
We will implement it as `F(n) = F(n - 1) + F(n - 2) + F(n - 3)`
Algorithm:
O( 3 ^ N ), where N is the given integer
For each function call, we are making 3 subsequent function calls. Hence the total number of recursive calls is ~3 ^ N
Hence the overall time complexity is O( 3 ^ N ).
O( N ), where N is the given integer
The space complexity of the recursion stack is ~N.
Hence the final space complexity is O( N )