
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.
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.
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
You do not need to print anything. It has already been taken care of. Just implement the given function.
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:
In this approach, we will try to create an array of N length, where the ith index will store the ‘i’th index in the array. We can intialise tribonacci[0], tribonacci[1] and tribonacci[2] as 0, 1, 1.
Algorithm:
In this approach, we will store only the last three values instead of an entire array. We can see from the previous approach that we only require last the three values of the sequence at any given moment.
Algorithm:
In this approach, if we take the ‘matrix’ [ [0, 1, 0], [0, 0, 1], [1, 1, 1] ] and multiply it by another matrix as [[Tn], [Tn+1], [Tn+2]], we get a matrix
Which is equal to:
Hence we can see that:
And so on….
Therefore Mn = ( matrix ^ n ) * ( M0 ),
And we know the fastest way to find exponent is in logarithmic time.
We will create a pow(matrix, n) function, where ‘matrix’ is the given matrix and ‘n’ is the exponent. We will also create multiplyMatrix(A, B) which returns a matrix which is the result of A*B
Algorithm: