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

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:

.

 

#include<iostream>
#include<cstring>
using namespace std;
#define For(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 10000
struct mat
{
    ll m[3][3];
};
mat a,e;
mat ans;
int n;
mat mul(mat a,mat b)
{
    mat c;
    mem(c.m,0);
    For(i,1,2)
    For(j,1,2)
    For(k,1,2)
    {
        c.m[i][j]+=a.m[i][k]*b.m[k][j]%mod;
        c.m[i][j]%=mod;
    }
    return c;
}
mat qmul(mat a,ll b)
{
    mat ans=e;
    while(b)
    {
        if(b&1)
            ans=mul(ans,a);
        a=mul(a,a);
        b>>=1;
    }
    return ans;
}

int main()
{
    For(i,1,2)e.m[i][i]=1;
    mem(a.m,0);
    a.m[1][1]=a.m[1][2]=a.m[2][1]=1;
    while(cin>>n&&n!=-1)
    {
        if(n==0)
        {
            cout<<0<<endl;
            continue;
        }
        mat ans=qmul(a,n-1);
        cout<<ans.m[1][1]%mod<<endl;
    }

    return 0;
}

矩阵快速幂入门题

posted @ 2018-03-19 22:20  planche  阅读(141)  评论(0编辑  收藏  举报