Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15397 | Accepted: 10803 |
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
- 普通的常系数线性齐次递推
- 建立矩阵快速幂加速
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long LL ;
typedef unsigned long long ULL ;
const int maxn = 1000 + 10 ;
const int inf = 0x3f3f3f3f ;
const int npos = -1 ;
const int mod = 1e4 ;
const int mxx = 100 + 5 ;
const double eps = 1e-6 ;
struct Matrix{
int n;
int a[mxx][mxx];
void reset(int x){
n=x;
memset(a,0,sizeof(a));
}
Matrix operator * (const Matrix X){
Matrix Y;
Y.reset(n);
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
if(a[i][k])
for(int j=0;j<n;j++)
if(X.a[k][j])
Y.a[i][j]=
((Y.a[i][j] + (a[i][k]*X.a[k][j])%mod)%mod + 2*mod)%mod;
return Y;
}
};
Matrix pow_mod(Matrix X, int k){
int n=X.n;
Matrix Y;
Y.reset(X.n);
for(int i=0;i<n;i++)
Y.a[i][i]=1;
while(k){
if(1&k)
Y=Y*X;
X=X*X;
k>>=1;
}
return Y;
}
int cal(int k){
if(k<2){
return k;
}else{
Matrix Y;
Y.reset(2);
Y.a[0][0]=1; Y.a[0][1]=1;
Y.a[1][0]=1; Y.a[1][1]=0;
Y=pow_mod(Y,k-1);
return Y.a[0][0];
}
}
int n, ans, f[2]={0,1};
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
while(~scanf("%d",&n) && -1!=n){
printf("%d\n",cal(n));
}
return 0;
}