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个Fibonacci数对10000的取余,由于n很大,简单模拟肯定不行,那么就引出了Fibonacci的另一种表示方法(题中已给),根据描述,我们只要求出2*2的矩阵{{1,1},{1,0}}^n就可以了。
由此引出新算法:矩阵快速幂(根据快速幂改编而来,快速幂计算的是数的n次方,而这个求的是矩阵的n次方)。
#include<stdio.h> #include<string.h> #include<queue> #include<math.h> #include<stdlib.h> #include<algorithm> using namespace std; const int N=1e6+10; const int INF=0x3f3f3f3f; const int MOD=1e4; typedef long long LL; struct node { LL m[2][2]; }ans, tmp, cnt; node Multiply(node a, node b) ///计算两个矩阵相乘之后的矩阵 { int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { cnt.m[i][j] = 0; for (k = 0; k < 2; k++) cnt.m[i][j] = (cnt.m[i][j]+a.m[i][k]*b.m[k][j])%MOD; } } return cnt; } LL Matrix_power(LL n) { ans.m[0][0] = ans.m[1][1] = 1; ans.m[0][1] = ans.m[1][0] = 0; tmp.m[0][0] = tmp.m[0][1] = tmp.m[1][0] = 1; tmp.m[1][1] = 0; while (n) ///和快速幂求法一致 { if (n % 2 != 0) ans = Multiply(ans, tmp); tmp = Multiply(tmp, tmp); n /= 2; } return ans.m[0][1]; ///由于第n个Fibonacci数存在于{Fn+1,Fn,Fn,Fn-1}中,所以我们返回(0,1)位置上的元素即可 } int main () { LL n, num; while (scanf("%lld", &n), n != -1) { num = Matrix_power(n); printf("%lld ", num); } return 0; }