矩阵乘法加速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\n",fibn(n-2));
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/sssy/p/7368034.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值