poj3070 Find the nth term of the Fibonacci sequence - the fast power of the matrix

Subject: http://poj.org/problem?id=3070

Speed ​​up recursion with fast exponentiation of matrices.

code show as below:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,p=10000;
struct Matrix{
    int a[3][3];
    Matrix operator * (const Matrix &y) const
    {
        Matrix x;
        memset(x.a,0,sizeof x.a);
        for(int i=1;i<=2;i++)
            for(int k=1;k<=2;k++)
                for(int j=1;j<=2;j++)
                    x.a[i][j]+=y.a[i][k]*a[k][j];
        return x;
    }
}m,years;
void mod()
{
    m.a[1][1]%=p;m.a[1][2]%=p;//
    m.a[2][1]%=p;m.a[2][2]%=p;
    ans.a[ 1 ][ 1 ]%=p;ans.a[ 2 ][ 1 ]%= p;
}
intmain ()
{
    while(scanf("%d",&n)==1)
    {
        if(n==-1)return 0;
        memset(m.a,0,sizeof m.a);
        memset(ans.a,0,sizeof ans.a);
        m.a[1][1]=1;m.a[1][2]=1;
        m.a[2][1]=1;m.a[2][2]=0;
        ans.a[1][1]=1;ans.a[2][1]=1;
        if(!n){printf("0\n");continue;}
        if(n==1){printf("1\n");continue;}
        if(n==2){printf("1\n");continue;}
        n--;//!
        while(n)
        {
            if(n&1)ans=ans*m;
            m=m*m;
            mod();
            n=(n>>1);
        }
        printf("%d\n",ans.a[2][1]%p);
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325190411&siteId=291194637