POJ ---3070 (矩阵乘法求Fibonacci 数列)

Fibonacci
 

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

思路:矩阵快速幂,没什么可说的。

 1 #include<cstdio>
 2 #include<string>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 typedef struct Matrix{
 8     int m[2][2];
 9     Matrix(){
10         memset(m, 0, sizeof(m));
11     }
12 }Matrix;
13 Matrix mtMul(Matrix A, Matrix B){
14     Matrix tmp;
15     for(int i = 0;i < 2;i ++)
16         for(int j = 0;j < 2;j ++)
17             for(int k = 0;k < 2;k ++){
18                 int t = (A.m[i][k] * B.m[k][j])%10000;
19                 tmp.m[i][j] = (tmp.m[i][j] + t)%10000;  
20             }
21     return tmp;
22 }
23 Matrix mtPow(Matrix A, int k){
24     if(k == 1) return A;
25     Matrix tmp = mtPow(A, k >> 1);
26     Matrix res = mtMul(tmp, tmp);
27     if(k & 1) res = mtMul(res, A);
28     return res;
29 }
30 int main(){
31     int n;
32     while(~scanf("%d", &n) && (n+1)){
33         if(n == 0) printf("0\n");
34         else{
35             Matrix M;
36             M.m[0][0] = M.m[0][1] = M.m[1][0] = 1;
37             M.m[1][1] = 0;
38             Matrix tmp = mtPow(M, n);
39             printf("%d\n", tmp.m[1][0]);
40         }
41     }
42     return 0;
43 }

 

 

posted on 2014-04-25 13:05  ~Love()  阅读(243)  评论(0编辑  收藏  举报

导航