• F[0]=0;

    F[1]=1;

    F[n]=F[n-1]+F[n-2], for n>1

    给出n (0<=n<=10000) 和 m (0<m<10000);求斐波那契数列第n项mod m的值(因为太大了);

  • #include<stdio.h>
  • #include<string.h>
  • // 矩阵快速幂
  • void xx(longlong a[][3],longlong b[][3],longlong m){
  • longlong tmp[3][3];
  • tmp[1][1]= tmp[1][2]= tmp[2][1]= tmp[2][2]=0;
  • for(int i =1; i <=2; i++){
  • for(int j =1; j <=2; j++){
  • for(int k =1; k <=2; k++){
  • tmp[i][j]+=(a[i][k]%m*b[k][j]%m)%m;
  • }
  • }
  • }
  • for(int i =1; i <=2; i++)
  • for(int j =1; j <=2; j++) a[i][j]= tmp[i][j]%m;
  • }
  • int main(){
  • // ans初值是单位矩阵
  • longlong T, ans[3][3], r[3][3], n, m;
  • r[1][2]= r[2][1]= r[2][2]= ans[1][1]= ans[2][2]=1;
  • r[1][1]= ans[1][2]= ans[2][1]=0;
  • scanf("%lld%lld",&n,&m);
  • if(!n){printf("%lld\n",0% m);return0;}
  • if(n ==1){printf("%lld\n",1% m);return0;}
  • n--;
  • while(n){
  • if(n &1) xx(ans, r, m);
  • n >>=1;
  • xx(r, r, m);
  • }
  • printf("%lld\n", ans[2][2]% m);
  • return0;
  • }
  • 相关文章:

    • 2021-10-16
    猜你喜欢
    相关资源
    相似解决方案