Given two integers, ‘N’ and ‘M’, your task is to find the sum of Fibonacci numbers between ‘fib(N)’ and ‘fib(M)’ where ‘fib(N)’ represents the Nth Fibonacci number and ‘fib(M)’ represents the Mth Fibonacci number. The sum is given by sum(N, M) = fib(N) + fib(N+1) + fib(N+2) … fib(M). Since the answer could be large, so you have to return the sum modulo 10^9 + 7.
The fibonacci relation is given by:
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2), n >= 2, where fib(n) represents the nth fibonacci number.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, which denote the start and end of the range.
Output format:
For each test case, print the sum of Fibonacci numbers between ‘fib(N)’ and ‘fib(M)’.
Print the output for each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 1000
0 <= N <= M <= 10^9
Where ‘T’ represents the number of test cases, and ‘N’ and ‘M’ represents the starting and ending of the range respectively.
Time Limit: 1 sec
2
2 6
0 5
19
12
For the first test case,
The Fibonacci numbers between fib(2) and fib(6) are {1, 2, 3, 5, 8}. Their sum is equal to 19. Hence the output is 19.
For the second test case,
The Fibonacci numbers between fib(0) and fib(5) are {0, 1, 1, 2, 3, 5}. Their sum is equal to 12. Hence the output is 12.
2
3 6
6 7
18
21
Find all the Fibonacci numbers recursively and add them.
Algorithm:
O(M*2^M), where ‘N’ and ‘M’ represent the start and the end of the range.
Since we are using a recursive function fibonacciNumbers() to calculate Fibonacci numbers from fib(N) to fib(M) which takes O(M*2^M) time. So overall time complexity will be O(M*2^M).
O(M), where ‘N’ and ‘M’ represent the start and the end of the range
Since we are using a recursive function and in the worst case, there can be O(M) states in the recursion stack. So, the overall space complexity will be O(M).