矩阵乘法加速fib数列

考虑矩阵(1,1)(1,0)

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define LL long long
const int mod = 1e9+7;
const int N = 2;
struct Matrix{
    int a[N][N];
    Matrix(){
        this -> clear();
    }
    void clear(){
        memset(a,0,sizeof(a));
    }
    void setone(){
        this ->clear();for(int i=0;i<N;++i)
            a[i][i]=1;
    }
    
    Matrix operator * (const Matrix &x) {
         Matrix c;
         for (int k=0;k<N;++k)
             for (int i=0;i<N;++i)
                 for (int j=0;j<N;++j)
                    c.a[i][j]=(c.a[i][j]+(LL)a[i][k]*x.a[k][j])%mod;
        return c;
    }   
};
int fibn(int x)
{
    Matrix a,b;
    a.clear();
    a.a[0][0]=a.a[0][1]=a.a[1][0]=1;
    b.setone();
    while(x)
    {
        if(x&1) b=b*a;
        a=a*a;
        x>>=1;
    }
    return (b.a[0][0]+b.a[0][1])%mod;
}   
int main()
{
    int n;
    while (~scanf("%d",&n))
    {
        if (n==1||n==2) puts("1");
        else printf("%d
",fibn(n-2));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/sssy/p/7368034.html