描述 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.
输入格式 InputFormat
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.
输出格式 OutputFormat
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).
样例输入 SampleInput
0
9
999999999
1000000000
-1
样例输出 SampleOutput
0
34
626
6875
代码 Code
矩阵快速幂。
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int i,j,t,n,m,l,r,k,z,y,x;
inline void read(int &x)
{
x=0;char ch=getchar();
while (ch<'0' || ch>'9') ch=getchar();
while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
}
const int mod=10000;
struct matrix
{
int s[5][5];
matrix operator * (matrix b) const
{
int i,j,t;
matrix ans;
memset(ans.s,0,sizeof(ans.s));
for (i=1;i<=n;i++) for (j=1;j<=n;j++) for (k=1;k<=n;k++)
ans.s[i][j]=(ans.s[i][j]+(s[i][k]*b.s[k][j])%mod)%mod;
return ans;
}
};
matrix a,b,c;
void qpow(int n)
{
int i,j,t;
while (n)
{
if (n&1) b=b*a;
a=a*a;
n>>=1;
}
}
int main()
{
scanf("%d",&x);
n=2;
while (x!=-1)
{
a.s[1][1]=0;a.s[1][2]=1;a.s[2][1]=1;a.s[2][2]=1;
memset(b.s,0,sizeof(b.s));
b=a;
qpow(x);
printf("%d\n",b.s[1][1]%mod);
scanf("%d",&x);
}
}