原题点这里 Time Limit: 1000MS Memory Limit: 65536K
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:
题目大意(百度机翻)
在斐波纳契数列的整数序列,F0 = 0,F1 = 1,和Fn = 1 + Fn Fn−2 n≥2。
例如,斐波那契数列的前十项是:0, 1, 1,2, 3, 5,8, 13, 21,34,…
斐波那契数列的另一个公式是
给定一个整数n,你的目标是计算FN的最后4个数字。
输入输入测试文件将包含多个测试用例。
每个测试案例是由单独的一行包含N(0≤N≤1000000000)。
文件结尾是由一个单一的行数−1表示。输出对于每个测试用例,输出FN的最后四个数字。
如果FN的最后四个数字都为零,则输出“0”;
否则,省略任何前导零(即,输出Fn mod 10000)。
样本输入
0
9
999999999
1000000000
- 1
示例输出
0
34
626
6875
纯模板
代码
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define Mod 10000
struct node
{
int v[3][3];
int m,l;
};
node get_mul(node a,node b)
{
node c;
c.m=a.m;c.l=b.l;
for(int i=1;i<=c.m;i++)
for(int j=1;j<=c.l;j++)
{
c.v[i][j]=0;
for(int k=1;k<=a.l;k++)
c.v[i][j]=(c.v[i][j]+a.v[i][k]*b.v[k][j])%Mod;
}
return c;
}
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(n==0) {printf("0\n");continue;}
if(n==-1) break;
node a,b,c;
a.m=a.l=2,a.v[1][1]=1,a.v[1][2]=1,a.v[2][1]=1,a.v[2][2]=0;
b.m=b.l=2,b.v[1][1]=1,b.v[1][2]=0,b.v[2][1]=0,b.v[2][2]=1;
c.m=2,c.l=1,c.v[1][1]=1,c.v[2][1]=0;
n--;
while(n)
{
if(n&1) b=get_mul(a,b);
a=get_mul(a,a);
n>>=1;
}
b=get_mul(b,c);
printf("%d\n",b.v[1][1]);
}
return 0;
}