<题目链接>
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
解题分析:
由于n很大,所以直接计算时不可行的,可以用矩阵快速幂来加速,并且,此题直接给出了矩阵的递推式,于是,我们只要按照题意构造矩阵即可。
#include <cstdio> #include <cstring> const int mod=10000; struct Matrix{ int m[5][5]; Matrix(){} Matrix(int x,int y,int z,int k){ m[0][0]=x; m[0][1]=y; m[1][0]=z; m[1][1]=k; } }; Matrix Mul(Matrix a,Matrix b){ Matrix temp; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ temp.m[i][j]=0; for(int k=0;k<2;k++){ temp.m[i][j]=(temp.m[i][j]+a.m[i][k]%mod*b.m[k][j]%mod)%mod; } } } return temp; } Matrix pow_Mul(Matrix x,int c){ Matrix tmp(1,0,0,1); while(c>0){ if(c&1){ tmp=Mul(tmp,x); } c>>=1; x=Mul(x,x); } return tmp; } int main(){ int n; while(scanf("%d",&n)!=EOF){ if(n==-1)break; int f[]={0,1,1,2}; if(n<=3){ printf("%d ",f[n]); continue; } Matrix init(f[3],f[2],f[2],f[1]); Matrix tmp(1,1,1,0); Matrix ans=Mul(pow_Mul(tmp,n-3),init); printf("%d ",ans.m[0][0]%mod); } return 0; }
2018-08-21