题目链接:http://poj.org/problem?id=3070
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
Hint
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:
.
解题思路:题目已经说得清楚,这里就讲讲思路吧。通过给出的递推式我们可以推导得到题目那个n次幂的矩阵的通项公式,记那个矩阵为A,所以问题转化成求An,然后就不自觉想到了矩阵快速幂,没错,无论n有多大,采用矩阵快速幂的做法就是一件很简单的事情。不过如果n值超过int最大值,要改成long long类型,避免数据溢出,其余代码不变。最后取结果矩阵右上角的值即为Fn对应的结果。
AC代码:
1 #include<iostream> 2 #include<string.h> 3 using namespace std; 4 const int mod=10000; 5 const int maxn=2;//2行2列式 6 int n; 7 struct Matrix 8 { 9 int m[maxn][maxn]; 10 }init; 11 Matrix mul(Matrix a,Matrix b)//矩阵相乘 12 { 13 Matrix c; 14 for(int i=0;i<maxn;i++){ 15 for(int j=0;j<maxn;j++){ 16 c.m[i][j]=0; 17 for(int k=0;k<maxn;k++) 18 c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j]%mod)%mod; 19 c.m[i][j]%=mod; 20 } 21 } 22 return c; 23 } 24 Matrix POW(Matrix a,int x) 25 { 26 Matrix b; 27 memset(b.m,0,sizeof(b.m)); 28 for(int i=0;i<maxn;++i)b.m[i][i]=1;//单位矩阵 29 while(x){ 30 if(x&1)b=mul(b,a); 31 a=mul(a,a); 32 x>>=1; 33 } 34 return b; 35 } 36 int main() 37 { 38 while(cin>>n && (n!=-1)){ 39 init.m[0][0]=1;init.m[0][1]=1;init.m[1][0]=1;init.m[1][1]=0;//初始化矩阵 40 Matrix res = POW(init,n);//矩阵快速幂 41 cout<<res.m[0][1]<<endl;//取右上角的值即可 42 } 43 return 0; 44 }