poj3070矩阵快速幂求斐波那契数列

 
Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13172   Accepted: 9368

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矩阵快速幂求斐波那契数列.

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


思路:没得说,矩阵快速幂

代码如下:

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int mod = 10000;
const int N = 2;//矩阵的维数,角标从0开始
struct Matrix
{
    __int64 v[N][N];
    Matrix()
    {
        memset(v,0,sizeof(v));
    }
};
//矩阵的乘法p1*p2
Matrix multi(Matrix p1,Matrix p2)
{
    Matrix res;
    for(int i=0;i<N;i++)
        for(int j=0;j<N;j++)
            if(p1.v[i][j])//代码优化,是0的话就不用计算
                for(int k=0;k<N;k++)
                    res.v[i][k]=(res.v[i][k]+(p1.v[i][j]*p2.v[j][k]))%mod;
    return res;
}
//矩阵的快速幂p^k
Matrix pow(Matrix p,__int64 k)
{
    Matrix t;
    for(int i=0;i<N;i++)//初始化为单位矩阵
        t.v[i][i]=1;
    while(k)
    {
        if(k&1)
            t=multi(t,p);
        p=multi(p,p);
        k=k>>1;
    }
    return t;
}


int main()
{
    __int64 n;
    Matrix e,ans;
    e.v[0][0]=e.v[0][1]=e.v[1][0]=1;
    e.v[1][1]=0;
    while(scanf("%I64dd",&n)!=EOF&&n!=-1)
    {
        ans = pow(e,n);
        printf("%I64d
",ans.v[0][1]);
    }
    return 0;
}