题目背景
大家都知道,斐波那契数列是满足如下性质的一个数列:
• f(1) = 1
• f(2) = 1
• f(n) = f(n-1) + f(n-2) (n ≥ 2 且 n 为整数)
题目描述
请你求出 f(n) mod 1000000007 的值。
输入输出格式
输入格式:·第 1 行:一个整数 n
输出格式:第 1 行: f(n) mod 1000000007 的值
输入输出样例
输入样例#1:
5
输出样例#1:
5
输入样例#2:
10
输出样例#2:
55
说明
对于 60% 的数据: n ≤ 92
对于 100% 的数据: n在long long(INT64)范围内。
n 的规模太大,需用矩阵快速幂。
附代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#define MAXN 5
#define MOD 1000000007
using namespace std;
struct node{
long long a[MAXN][MAXN];
}ans,base,s;
inline long long read(){
long long date=0,w=1;char c=0;
while(c<'0'||c>'9'){if(c=='-')w=-1;c=getchar();}
while(c>='0'&&c<='9'){date=date*10+c-'0';c=getchar();}
return date*w;
}
node operator *(const node &x,const node &y){
node ret;
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++){
ret.a[i][j]=0;
for(int k=1;k<=2;k++){
ret.a[i][j]+=x.a[i][k]%MOD*y.a[k][j]%MOD;
ret.a[i][j]%=MOD;
}
}
return ret;
}
void mexp(long long k){
for(int i=1;i<=2;i++)s.a[i][i]=1;
base.a[1][2]=base.a[2][1]=base.a[2][2]=1;
while(k){
if(k&1)s=s*base;
base=base*base;
k>>=1;
}
}
int main(){
long long k;
k=read();
if(k==1||k==2){
printf("1\n");
return 0;
}
mexp(k-2);
ans.a[1][1]=ans.a[1][2]=1;
ans=ans*s;
printf("%d\n",ans.a[1][2]);
return 0;
}