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

本文介绍了一种利用矩阵快速幂解决特定递推数列的方法,通过C++代码实现了一个具体的例子,展示了如何初始化矩阵,以及如何进行快速幂运算来高效求解大数值问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值