Ninja observed the prices of a certain stock for some days. He found an interesting pattern in the prices of the stock. Let P(i) be the price of the stock on the βithβ day. He observed that
P(i) = P(i-1) + P(i-2) + P(i-1) * P(i-2)
You are given the stock prices on the first day and the second day. Your task is to determine the price of the stock on the βNthβ day if the prices followed the same pattern.
Input Format :
The first line contains an integer βTβ, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains three space-separated integers, βAβ, βBβ and βNβ Where βAβ and βBβ denote the prices on the first and second days respectively. βNβ denotes the day on which the stock price needs to be calculated.
Output Format :
For each test case, print a single integer, denoting the price of the stock on the βNthβ day. Since the answer can be very large, calculate the answer modulo 10^9+7.
Output for each test case will be printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= A,B, <= 10^9
3 <= N <= 5000
Time Limit: 1sec
1
1 7 3
15
In the given test case, the price on day 1 is 1, and the price on day 2 is 7. We can calculate the price on day 3 using these two values. Price on day 3 will be 1 + 7 + (1*7) = 15.
1
1 3 4
31
In the given test case, the price on day 1 is 1, and the price on day 2 is 3. We can calculate the price on day 3 using these two values. Price on day 3 will be 1 + 3 + (1*3) = 7. Similarly, price on day 4 will be 3 + 7 + (3*7) = 31.
Find the price for previous days by recursively calling the function for that day.
Approach:
The approach is to simply call the function recursively to find the prices on the last day and the second last day. These two values can then be used to calculate the prices for the current day.
Steps:
O(2 ^ N), where βNβ is the day for which the price is to be calculated.
We are recursively calling the function for smaller subproblems which in turn are calling the same function for even smaller subproblems. This takes O(2^N) time as for every function call, we need values of two smaller subproblems.
O(2 ^ N), where βNβ is the day for which the price is to be calculated.
We need extra space for the recursion stack.