Function value

3.2

38 votes
Modular Exponentiation, Medium, Matrix Exponentiation, Number Theory, Mathematics
Problem

A function f is defined by the following recurrence relations:

f(n+2)=2f(n+1)f(n)+2, if n is even

f(n+2)=3f(n), if n is odd

where n>0 and f(1)=f(2)=1
You have to answer multiple queries. In each query, you are given two integers L and R and you are required to determine the value of (f(L)+f(L+1)+...+f(R1)+f(R)) modulo P.

P is fixed for all queries.

Input format

First line: Two integers T (1T1000) and P (1P109), where T represents the number of queries
Each of the next T lines: Two integers L and R (1LR1018)

Output format

For each query, print the value of (f(L)+f(L+1)+...+f(R1)+f(R)) modulo P in a new line.

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

As 3 is odd, f(3) = 3 * f(1) = 3 * 1 = 3

As 4 is even, f(4) = 2*f(3) - f(2) + 2 = 2*3 - 1 + 2 = 7

So, when L is 3, R is 4 and P is 100000007, answer is (3 + 7)%100000007 = 10

Similarly, when L is 4, R is 4 and P is 100000007, answer is (7) %100000007 = 7

Editor Image

?