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, …
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
求 Fibonacci数列,转化为矩阵相乘,利用快速幂的思想
f2 = f0 + f1 -----> (f0 f1)(1 1) -------> (f2 , f1)
(1 0)
f3 = f1 + f2 -----> (f0 f1)(1 1) (1 1) -------> (f3 , f2)
(1 0) (1 0)
f0 = 0 , f1 = 1;
#include <iostream>
#include <cstdio>
#include <cstring>
#define Mod 10000
int n;
struct Node
{
int m[3][3];
int x;
int y;
}pt , st , dt;
Node Pow(Node a, Node b)
{
memset(dt.m , 0 , sizeof(dt.m));
dt.x = a.x;
dt.y = b.y;
for(int i = 1 ; i <= a.x; i++)
{
for(int k = 1; k <= a.y; k++)
{
if(a.m[i][k] == 0)
continue;
{
for(int j = 1; j <= b.y; j++)
{
dt.m[i][j] = ((dt.m[i][j] + a.m[i][k] * b.m[k][j]) % Mod) % Mod;
}
}
}
}
return dt;
}
void quickpow(int n)
{
while(n)
{
if(n % 2 == 1)
pt = Pow(st , pt);
n = n / 2;
st = Pow(st , st);
}
}
int main()
{
while(~scanf("%d",&n) && n != -1)
{
memset(pt.m , 0 ,sizeof(pt.m));
memset(st.m , 0 , sizeof(st.m));
pt.m[1][1] = pt.m[2][2] = 1; //初始化单位矩阵
st.m[1][1] = st.m[1][2] = st.m[2][1] = 1;//已知矩阵
pt.x = pt.y = 2;
st.x = st.y = 2; //矩阵的行列长度
quickpow(n);
printf("%d\n",pt.m[1][2]%Mod);
}
return 0;
}