思路:矩阵快速幂的入门题
#include<iostream> #include<cstdio> #include<cstring> using namespace std; struct Mat { int a[2][2]; //矩阵大小 }; int n; const int mod = 10000; Mat mul(Mat a,Mat b) { Mat t; memset(t.a,0,sizeof(t.a)); for(int i = 0;i<n;i++) { for(int k = 0;k<n;k++) { if(a.a[i][k]) for(int j = 0;j<n;j++) { t.a[i][j]+=a.a[i][k]*b.a[k][j]; if(t.a[i][j]>=mod) t.a[i][j]%=mod; } } } return t; } Mat expo(Mat p,int k) { if(k==1)return p; Mat e; memset(e.a,0,sizeof(e.a)); for(int i = 0;i<n;i++) //初始化单位矩阵 e.a[i][i]=1; if(k==0)return e; while(k) { if(k&1) e = mul(p,e); p = mul(p,p); k>>=1; } return e; } int main() { int k; n=2; while(scanf("%d",&k)!=EOF && k!=-1) { if(k==0) printf("0\n"); else { Mat p; p.a[0][0]=p.a[0][1]=p.a[1][0]=1; p.a[1][1]=0; Mat ans = expo(p,k); /*for(int i = 0;i<n;i++,printf("\n")) for(int j = 0;j<n;j++) printf("%d ",ans.a[i][j]);*/ printf("%d\n",ans.a[0][1]); } } }
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., printFn mod 10000).
Sample Input
0 9 999999999 1000000000 -1Sample Output
0 34 626 6875Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
