转-知乎王希:https://www.zhihu.com/question/28062458
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:
.
Source
Stanford Local 2006
本题用到矩阵的快速幂:
首先,斐波那契可以由矩阵求得:
由此推得
初始矩阵为,记为E,那么E^2 为,E^3为,E^4为......可以发现,(0,1)位置的数是第i个斐波那契数。
问题转化为求初始矩阵的n次方,是几次方斐波那契数对应的就是就是矩阵的位置
更详细的快速幂讲解参考https://www.cnblogs.com/cmmdc/p/6936196.html
#include <iostream>
using namespace std;
const int MOD = 10000;///最后的模
struct matrix///定义矩阵结构体
{
int m[2][2];
} ans, base;
matrix multi(matrix a, matrix b)///定义矩阵乘法。a,b代表两个矩阵
{
matrix tmp;///求和矩阵
for(int i = 0; i < 2; i++)
{
///第一个矩阵的行
for(int j = 0; j < 2; j++)
{
///第二个矩阵的列
tmp.m[i][j] = 0;///和初始化
for(int k = 0; k < 2; k++)
tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
}///注意这时候要取一次模
}
return tmp;///返回结构体和的矩阵
}
int fast_mod(int n)///求基础矩阵base的n次幂
{
base.m[0][0] = base.m[0][1] = base.m[1][0] = 1;
base.m[1][1] = 0;///构造初始矩阵
ans.m[0][0] = ans.m[1][1] = 1;///普通快速幂ans初始化为1
ans.m[0][1] = ans.m[1][0] = 0;///那么矩阵ans就应该初始化为单位矩阵
while(n)
{
if(n&1) ///实现ans*=t;其中要先把ans赋值给tmp,然后用ans=tmp*t
ans = multi(ans, base);
base = multi(base, base);///全部转化为矩阵乘法
n >>= 1;
}
return ans.m[0][1];///返回矩阵的(0,1)位置
}
int main()
{
int n;
while(cin>>n)
{
if(n==-1)
return 0;
cout<<fast_mod(n)<<endl;
}
}