poj 3070 Fibonacci

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 struct Matrix{int m[maxn][maxn];}init;int n;
 7 Matrix mul(Matrix a,Matrix b){//矩阵相乘
 8     Matrix c;
 9     for(int i=0;i<maxn;i++){//第一个矩阵的行
10         for(int j=0;j<maxn;j++){//第二个矩阵的列
11             c.m[i][j]=0;
12             for(int k=0;k<maxn;k++)
13                 c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%mod;
14         }
15     }
16     return c;
17 }
18 Matrix POW(Matrix a,int x){
19     Matrix b;memset(b.m,0,sizeof(b.m));
20     for(int i=0;i<maxn;++i)b.m[i][i]=1;//单位矩阵
21     while(x){
22         if(x&1)b=mul(b,a);
23         a=mul(a,a);
24         x>>=1;
25     }
26     return b;
27 }
28 int main(){
29     while(cin>>n&&(n!=-1)){
30         init.m[0][0]=1;init.m[0][1]=1;init.m[1][0]=1;init.m[1][1]=0;//初始化矩阵
31         Matrix res = POW(init,n);//矩阵快速幂
32         cout<<res.m[0][1]<<endl;//取右上角的值即可
33     }
34     return 0;
35 }
原文地址:https://www.cnblogs.com/acgoto/p/9080905.html