码迷,mamicode.com
首页 > 其他好文 > 详细

poj 3070 Fibonacci 矩阵快速幂

时间:2015-04-08 00:40:52      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://poj.org/problem?id=3070

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).

题意描述:菲波那契数列可以用题中那个矩阵计算得到,给出n(n可以超大),求出Fn。

算法分析:赤果果的矩阵快速幂。如果对矩阵快速幂不熟悉的话,可以先百度看看讲解。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<cmath>
 6 #include<algorithm>
 7 using namespace std;
 8 const int mod=10000;
 9 
10 int n;
11 struct matrix
12 {
13     int an[2][2];
14 }res;
15 matrix multiply(matrix a,matrix b)
16 {
17     matrix s;
18     memset(s.an,0,sizeof(s.an));
19     for (int i=0 ;i<2 ;i++)
20     {
21         for (int j=0 ;j<2 ;j++)
22         {
23             for (int k=0 ;k<2 ;k++)
24             {
25                 s.an[i][j] += a.an[i][k]*b.an[k][j];
26                 if (s.an[i][j]>mod) s.an[i][j]%=mod;
27             }
28         }
29     }
30     return s;
31 }
32 void calc(int n)
33 {
34     matrix sum;
35     for (int i=0 ;i<2 ;i++)
36     {
37         for (int j=0 ;j<2 ;j++)
38         sum.an[i][j]= i==j ? 1 : 0 ;
39     }
40     for (int i=0 ;i<2 ;i++)
41     {
42         for (int j=0 ;j<2 ;j++)
43         res.an[i][j]=1;
44     }
45     res.an[1][1]=0;
46     while (n)
47     {
48         if (n&1) sum=multiply(sum,res);
49         n >>= 1;
50         res=multiply(res,res);
51     }
52     printf("%d\n",sum.an[1][0]%mod);
53 }
54 
55 int main()
56 {
57     while (scanf("%d",&n)!=EOF && n!=-1)
58     {
59         calc(n);
60     }
61     return 0;
62 }

 

poj 3070 Fibonacci 矩阵快速幂

标签:

原文地址:http://www.cnblogs.com/huangxf/p/4400942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!