矩阵二分幂求Fib(非结构体版)

矩阵二分幂求fib模板(0<=n<=10^9),如果取模的数的平方没超过long long,那么n可以满足条件为n<=10^18,速度很快。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define ll long long
#define mod 1000000007
using namespace std;
ll solve(ll n)
{
	ll Ans[2][2]={1,0,0,1};
	ll Base[2][2]={0,1,1,1};
	ll temp00=0,temp01=0,temp10=0,temp11=0;
	while(n)
	{
		if(n&1)
		{
			temp00=Ans[0][0],temp01=Ans[0][1];
			temp10=Ans[1][0],temp11=Ans[1][1];
			Ans[0][0]=(temp00*Base[0][0]+temp01*Base[1][0])%mod;
			Ans[0][1]=(temp00*Base[0][1]+temp01*Base[1][1])%mod;
			Ans[1][0]=(temp10*Base[0][0]+temp11*Base[1][0])%mod;
			Ans[1][1]=(temp10*Base[0][1]+temp11*Base[1][1])%mod;
		}
		temp00=Base[0][0],temp01=Base[0][1];
		temp10=Base[1][0],temp11=Base[1][1];
		Base[0][0]=(temp00*temp00+temp01*temp10)%mod;
		Base[0][1]=(temp00*temp01+temp01*temp11)%mod;
		Base[1][0]=(temp10*temp00+temp11*temp10)%mod;
		Base[1][1]=(temp10*temp01+temp11*temp11)%mod;
		n>>=1;
	}
	return Ans[0][1];
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
	{
	    ll n;
	    scanf("%lld",&n);
        ll ans = solve(n);
        printf("%lld\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值