题目传送门
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 , … 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … 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
题意
- 利用矩阵快速幂求Fibonacci数列第 n 项
题解
- 很简单的矩阵快速幂,可以按照题目给的矩阵构造,也可以像我这样构造,如下图
AC-Code
#include <bits/stdc++.h>
//#pragma GCC optimize("O3")
//#pragma G++ optimize("O3")
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
#define ll long long
#define RI register int
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);const int maxn = 3;
const int mod = 1e4;
#define mod(x) ((x)%mod)struct mat {
int m[maxn][maxn];mat() {
memset(m, 0, sizeof m);}
}unit;mat operator * (mat a, mat b) {
mat ret;ll x;for (ll i = 0; i < maxn; ++i)for (ll j = 0; j < maxn; ++j) {
x = 0;for (ll k = 0; k < maxn; ++k)x += mod((ll)a.m[i][k] * b.m[k][j]);ret.m[i][j] = mod(x);}return ret;
}void init_unit() {
for (int i = 0; i < maxn; ++i)unit.m[i][i] = 1;
}mat pow_mat(mat a, ll n) {
mat ret = unit;while (n) {
if (n & 1) ret = ret * a;a = a * a;n >>= 1;}return ret;
}int main() {
ios;int n;init_unit();while (cin >> n && n != -1) {
if (n == 0) puts("0");else if (n == 1) puts("1");else if (n == 2) puts("1");else {
mat a, b;b.m[0][0] = 1, b.m[0][1] = 1, b.m[0][2] = 0;b.m[1][0] = 1, b.m[1][1] = 0, b.m[1][2] = 1;b.m[2][0] = 0, b.m[2][1] = 0, b.m[2][2] = 0;a.m[0][0] = 1, a.m[0][1] = 1, a.m[0][2] = 0;b = pow_mat(b, n - 2);a = a * b;cout << mod(a.m[0][0]) << endl;}}return 0;
}