POJ3070 Fibonacci

POJ3070 Fibonacci

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13731   Accepted: 9727

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

POJ3070 Fibonacci.

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

POJ3070 Fibonacci.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

POJ3070 Fibonacci.

Source

矩阵乘法入门题。

hint已经写明了解法

 1 /*by SilverN*/
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 #include<vector>
 8 using namespace std;
 9 const int mod=1e4;
10 const int mxn=240;
11 struct mat{
12     int s[3][3];
13     mat(){memset(s,0,sizeof s);}
14 };
15 mat operator * (const mat a,const mat b){
16     mat c;
17     for(int i=1;i<=2;i++)
18      for(int j=1;j<=2;j++)
19        for(int k=1;k<=2;k++){
20         (c.s[i][j]+=a.s[i][k]*b.s[k][j])%=mod;
21        }
22     return c;
23 }
24 int n;
25 int main(){
26     int i,j;
27     while(scanf("%d",&n) && n!=-1){
28         mat a,b;
29         a.s[1][1]=1;a.s[1][2]=1;a.s[2][1]=1;a.s[2][2]=0;
30         b.s[1][1]=1;b.s[1][2]=0;b.s[2][1]=0;b.s[2][2]=1;
31         for(;n;n>>=1,a=a*a)
32             if(n&1)b=b*a;
33         printf("%d
",b.s[2][1]);
34     }
35     return 0;
36 }