Fibonacci Sequence III
T i m e Time Time L i m i t : 10000 M S Limit:10000MS Limit:10000MS M e m o r y Memory Memory L i m i t : 65536 K Limit:65536K Limit:65536K
C a s e Case Case T i m e Time Time L i m i t : 1000 M S Limit:1000MS Limit:1000MS
Description
Find the sequence f [n] = f [n − 1] + f [n − 2] + 1 f[n]=f[n-1]+f[n-2]+1f[n]=f[n−1]+f[n−2]+1 The first ofNNN items.f [1] = 1, f [2] = 1 f[1]=1,f[2]=1f[1]=1,f[2]=1.
Input
n ( 1 < n < 2 31 − 1 ) n(1<n<2^{31-1}) n(1<n<231−1)
Output
The first N NN item resultmod modmod 9973 9973 9973
Sample Input
12345
Sample Output
8932
analysis:
Matrix multiplication and this template is similar to
the same considerations matrix [fn - 1, fn - 2 , 1] [f_ {n-1}, f_ {n-2}, 1][fn−1,fn−2,1 ]
Multiply a certain matrix to get
[fn − 1, fn, 1] = [fn − 1, fn − 2 + fn − 1, 1] [f_{n-1},f_n,1]=[f_{n- 1},f_{n-2}+f_{n-1},1][fn−1,fn,1]=[fn−1,fn−2+fn−1,1 ] It is
easy to get the matrix as:
0, 1, 0 0,1,00,1,0
1 , 1 , 0 1,1,0 1,1,0
0 , 1 , 1 0,1,1 0,1,1
Thenjustdomatrix multiplicationdirectly
CODE:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int mod=9973;
long long n;
struct matrix{
long long n,m;
long long G[11][11];
}base,A,B;
matrix operator *(matrix a,matrix b)
{
matrix C;
C.n=a.n;C.m=b.m;
for(int i=1;i<=C.n;i++)
for(int j=1;j<=C.m;j++)
C.G[i][j]=0;
for(int k=1;k<=a.m;k++)
for(int i=1;i<=a.n;i++)
for(int j=1;j<=b.m;j++)
C.G[i][j]=(C.G[i][j]+a.G[i][k]*b.G[k][j]%mod)%mod; //矩阵乘法
return C;
}
void ksm(long long x){
if(x==1){
A=base;
return;
}
ksm(x/2);
A=A*A; //快速幂
if(x&1) A=A*base;
}
int main(){
scanf("%lld",&n);
base.n=3;base.m=3;
base.G[1][1]=0;base.G[1][2]=1;base.G[1][3]=0;
base.G[2][1]=1;base.G[2][2]=1;base.G[2][3]=0; //乘的矩阵
base.G[3][1]=0;base.G[3][2]=1;base.G[3][3]=1;
if(n<=2){
printf("1");
return 0;
}
else{
B.m=3;B.n=1;
B.G[1][1]=1;B.G[1][2]=1;B.G[1][3]=1; //设的矩阵
ksm(n-1);
B=B*A;
printf("%lld",B.G[1][1]);
}
return 0;
}