poj3070

Fibonacci

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6131 Accepted: 4296

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:

.

Source


呃,矩阵乘法快速幂嘛

很好写
1A
#include <cstdio>
#include 
<cstdlib>
#include 
<cstring>
#include 
<cmath>
#include 
<ctime>
#include 
<cassert>
#include 
<iostream>
#include 
<sstream>
#include 
<fstream>
#include 
<map>
#include 
<set>
#include 
<vector>
#include 
<queue>
#include 
<algorithm>
#include 
<iomanip>
using namespace std;

struct node
{
    
int a,b,c,d;
}
;
int n;
node mul(node t1,node t2)
{
    node tmp;
    tmp.a
=t1.a*t2.a+t1.b*t2.c;
    tmp.b
=t1.a*t2.b+t1.b*t2.d;
    tmp.c
=t1.a*t2.c+t1.c*t2.d;
    tmp.d
=t1.b*t2.c+t1.d*t2.d;
    tmp.a
=tmp.a%10000;
    tmp.b
=tmp.b%10000;
    tmp.c
=tmp.c%10000;
    tmp.d
=tmp.d%10000;
    
return tmp;
}

node 
get(node a1,int k)
{
    node tmp;
    
if(k==1)
    
{
        
return a1;
    }

    
else if(k==2return mul(a1,a1);
    
else
    
{
        tmp
=get(a1,k/2);
        
if(k&1)
            
return mul(mul(tmp,tmp),a1);
        
else return mul(tmp,tmp);
    }

}

int main()
{
    node ans,a;
    a.a
=1;
    a.b
=1;
    a.c
=1;
    a.d
=0;
    
while(scanf("%d",&n)!=EOF&&n!=-1)
    
{
        
if(n==0)
        
{
            printf(
"0\n");
            
continue;
        }

        ans
=get(a,n-1);
        printf(
"%d\n",ans.a);
    }

    
return 0;
}

posted on 2012-07-20 23:16 jh818012 阅读(203) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年7月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿

文章档案(85)

搜索

最新评论