1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 using namespace std;
7 void read(int &n)
8 {
9 char c='+';int x=0;bool flag=0;
10 while(c<'0'||c>'9'){c=getchar();if(c=='-')flag=1;}
11 while(c>='0'&&c<='9'){x=x*10+(c-48);c=getchar();}
12 flag==1?n=-x:n=x;
13 }
14 void Matrix_mul(int a[2][2],int b[2][2],int mod)
15 {
16 int c[2][2];
17 memset(c,0,sizeof(c));
18 for(int i=0;i<2;i++)
19 for(int j=0;j<2;j++)
20 for(int k=0;k<2;k++)
21 c[i][j]=(c[i][j]+(a[i][k]*b[k][j])%mod)%mod;
22 for(int i=0;i<2;i++)
23 for(int j=0;j<2;j++)
24 a[i][j]=c[i][j];
25 }
26 int Matrix_fastpow(int n,int q)
27 {
28 int a[2][2]={1,1,1,0};
29 int ans[2][2]={1,0,1,0};
30 while(n)
31 {
32 if(n&1)
33 Matrix_mul(ans,a,q);
34 Matrix_mul(a,a,q);
35 n>>=1;
36 }
37 //cout<<ans[0][1]<<endl;
38 return ans[0][1];
39 }
40 int main()
41 {
42 int T,n,q;
43 read(T);
44 while(T--)
45 {
46 read(n);read(q);
47 n++;
48 printf("%d\n",Matrix_fastpow(n,q));
49 }
50 return 0;
51 }