矩阵乘法,好久没写过了,不过重要的还是找到规律。
http://acm.hdu.edu.cn/showproblem.php?pid=2855
因为(a+1)^n=+
*a^1+
*a^2+....+
*a^n;
所以把F(k)带入之后再化简就可得到
然后就可以用矩阵乘法求斐波那契数列了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # include<stdio.h> 2 # include<string.h> 3 # include<stdlib.h> 4 int M; 5 struct matrix{ 6 int a[2][2]; 7 }; 8 matrix multi(matrix m1,matrix m2) 9 { 10 int i,j,k; 11 matrix mm; 12 for(i=0;i<2;i++) 13 { 14 for(j=0;j<2;j++) 15 { 16 mm.a[i][j]=0; 17 for(k=0;k<2;k++) 18 { 19 mm.a[i][j]+=m1.a[i][k]*m2.a[k][j]; 20 mm.a[i][j]%=M; 21 } 22 } 23 } 24 return mm; 25 } 26 matrix cal(matrix ma,int m) 27 { 28 int ans; 29 matrix m1; 30 m1.a[0][0]=1; 31 m1.a[0][1]=0; 32 m1.a[1][0]=0; 33 m1.a[1][1]=1; 34 while(m) 35 { 36 ans=m%2; 37 if(ans) m1=multi(m1,ma); 38 ma=multi(ma,ma); 39 m/=2; 40 } 41 return m1; 42 } 43 int main() 44 { 45 int n,ncase,ans; 46 scanf("%d",&ncase); 47 matrix m1; 48 while(ncase--) 49 { 50 scanf("%d%d",&n,&M); 51 m1.a[0][0]=1; 52 m1.a[0][1]=1; 53 m1.a[1][0]=1; 54 m1.a[1][1]=0; 55 n*=2; 56 if(n==0) {printf("0\n");continue;} 57 if(n==2) {printf("%d\n",1%M);continue;} 58 //(f[n],f[n-1])=(f[2],f[1])*m1^(n-2) 59 m1=cal(m1,n-2); 60 ans=(m1.a[0][0]+m1.a[1][0])%M; 61 printf("%d\n",ans); 62 } 63 return 0; 64 }