传送门
求斐波那契数列,矩阵快速幂模板题。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll n,MOD;
struct matrix {
ll x[2][2];
matrix mult(matrix a,matrix b,ll MOD) {
matrix c;
memset(c.x,0,sizeof(c.x));
for (int i=0;i<2;++i)
for (int j=0;j<2;++j)
for (int k=0;k<2;++k)
c.x[i][j]=(c.x[i][j]+a.x[i][k]*b.x[k][j]%MOD)%MOD;
return c;
}
ll fpow(ll n,ll MOD) {
matrix a,ans;
a.x[0][0]=a.x[0][1]=a.x[1][0]=1,a.x[1][1]=0;
ans.x[0][0]=ans.x[1][1]=1,ans.x[1][0]=ans.x[0][1]=0;
while (n) {
if (n&1) ans=ans.mult(ans,a,MOD);
n>>=1,a=a.mult(a,a,MOD);
}
return ans.x[0][1];
}
};
matrix FF;
int main() {
int kase;
scanf("%d",&kase);
while (kase--) {
scanf("%lld%lld",&n,&MOD);++n;
printf("%lld\n",FF.fpow(n,MOD));
}
return 0;
}