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
/* 快速幂模板应用 */ /************************************************ Author :powatr Created Time :2015-8-5 21:06:30 File Name :b.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 const int N = 2; typedef long long ll; const int MAX = 50; ll n; const int INF = 0x3f3f3f3f; const int mod = 1e4; struct Matrix { ll a[2][2]; void inti() { a[0][0] = a[0][1] = a[1][0] = 1; a[1][1] = 0; } }matrix; Matrix mul(Matrix a, Matrix b)//矩阵乘法 { Matrix ans; for(int i = 0 ; i < N; i++) for(int j = 0 ; j <N ;j++){ ans.a[i][j] = 0; for(int k = 0; k < N; k++){ if(a.a[i][k] == 0 || b.a[k][j] == 0) continue; ans.a[i][j] += a.a[i][k] * b.a[k][j]; ans.a[i][j] %= mod; } } return ans; } Matrix add(Matrix a, Matrix b) //矩阵加法 { int i, j, k; Matrix ans; for(int i = 0 ; i < N; i++) for(int j = 0 ; j < N; j++){ ans.a[i][j] = a.a[i][j] + b.a[i][j]; ans.a[i][j] %= mod; } return ans; } Matrix pow(Matrix a, int n) // 矩阵快速幂 { Matrix ret; ret.a[0][0] = ret.a[1][1] = 1; ret.a[0][1] = ret.a[1][0] = 0; while(n){ if(n&1) ret = mul(ret, a); n>>= 1; a = mul(a, a); } return ret; } Matrix sum(Matrix a, int n)//矩阵幂和 { int m; Matrix ans, pre; if(n == 1) return a; m = n >> 1; pre = sum(a, m); ans = add(pre, mul(pre, pow(a, m))); if(n&1) ans = add(ans, pow(a, n)); return ans; } void output(Matrix a) //输出 { for(int i = 0 ; i < n; i++) for(int j = 0 ; j < n ; j++) printf("%d%c",a.a[i][j], j == n -1 ? ‘\n‘ : ‘ ‘); } int main() { Matrix ans; while(~scanf("%I64d", &n) && ~n){ ans.inti(); Matrix d = pow(ans, n); printf("%I64d\n", d.a[0][1]); } return 0; }