大数斐波那契【矩阵快速幂】

来源:互联网 发布:刺客信条4优化补丁 编辑:程序博客网 时间:2024/05/16 09:05
#include <bits/stdc++.h>using namespace std;const int N = 4 ;long long int n;struct xx{    int a[N][N];} ori,res;xx mul(xx x,xx y){    xx temp;    memset(temp.a,0,sizeof(temp.a));    for(int i=0; i<N; i++)    {        for(int j=0; j<N; j++)        {            for(int k=0; k<N; k++)            {                temp.a[i][j]+=x.a[i][k]*y.a[k][j];                temp.a[i][j]=temp.a[i][j]%1000000007;            }        }    }    return temp;}void init(){    ori.a[0][0] = 1, ori.a[0][1] = 1;    ori.a[1][0] = 1, ori.a[1][1] = 0;    for(int i=0; i<N; i++)    {        for(int j=0; j<N; j++)        {            res.a[i][j]=i==j?1:0;        }    }}void calc(long long k){    while(k)    {        if(k%2==1)                           {            res=mul(ori,res);            k-=1;        }        else        {            ori=mul(ori,ori);            k/=2;        }    }    printf("%d\n", res.a[0][0]);}int main(){    int t;    cin>>t;    while(t--)    {        cin>>n;        init();        calc(n);    }}

原创粉丝点击