FIBTWIST - Fibonacci With a Twist

Fibonacci numbers are given by 

  • f(n) = f(n-1) + f(n-2)

with f(0) = 0 and f(1) = 1.

first number of series ------ 0  1  1  2  3  5  8  13 

Now let's have a new series called "Fibonacci Twist" which is given by 

  • ft(n) = ft(n-1) + ft(n-2) + (n-1)

with ft(0) = 0 and ft(1) = 1.

with first few number in the series ----- 0  1  2  5  10  19  34  59 

Now your task is to find ft(n).

Since the number can be big you have to find the result mod M.

Input

first line having single number 't' -- number of test cases.

Next t lines have 2 number each 'n' and 'M'

Output

Single number given the n-th term mod M

Example

Input:
3
5 20
10 77
15 111

Output:
19
45
69

Constraints

  • 10 <= t <= 100
  • 0 <= n <= 10^9
  • 100 <= M <= 10^9

Explanation

  1. ft(5) is 19. 19 % 20 = 19
  2. ft(10) is 276. 276 % 77 = 45
  3. ft(15) is 3177. 3177 % 111 = 69

Added by:Devil D
Date:2012-04-19
Time limit:0.100s-1s
Source limit:20000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Own

hide comments
2012-11-23 12:36:53 Pranshul Agarwal
AC in 0.01 sec with 2X2 matrix.. :D
2012-07-21 11:45:54 007: Name stolen
please check my solution its giving NZEC
http://www.spoj.pl/files/src/7352268/
2012-06-30 19:45:45 Gurpreet Singh
Please check my submissions. Don't know why its getting WA. I have checked it using data type as 'int' and 'long long'. Yet WA...
2012-05-31 03:44:00 Suraj D
@Problem Setter. Could you please tell me where I fail? Submission Id 7065432. Thanks.
2012-05-28 07:46:26 Adrian Jaskó³ka
TO PROBLEMSETTER:
Test cases are weak. Look at my submission 7050497. I have there table int c[3][3] (instead of long long!).
1
1000000000 1000000007
output should be 21, and my code is giving 347003493.

Last edit: 2012-05-28 07:47:01
2012-05-18 08:39:26 Aditya Pande
AC in 0.01 s

Last edit: 2012-10-02 06:54:56
2012-05-02 10:38:49 Paras Sharma
Can you please check my submission : 6934365

It should work.
------

Be careful with the limits and checks.
you are getting wrong answer for 1 input in test case 1.
your logic may also give TLE ...


Last edit: 2012-05-12 08:56:28
2012-04-28 07:21:41 Saurabh Jain
AC.:)

Last edit: 2012-06-24 07:12:53
2012-04-20 19:51:12 Pranay
@Tarun: yes
2012-04-20 17:21:17 Tarun Chabarwal
can it be solved with lower than 4x4 matrix?
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.