矩阵二分幂求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;
}