矩阵乘法 快速幂 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, …
Given two integers n and m, your goal is to compute the value of  Fn mod m.

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) and m(where 0<m<=10000). The end-of-file is denoted by a single line containing the number −1 -1.

Output

 For each test case, print the value of Fn%m one pre line, omit any leading zeros.

Sample Input
Copy sample input to clipboard
0 10000
9 10000
999999999 10000
1000000000 10000
-1 -1
Sample Output
0
34
626
6875
#include<iostream>
#include<cstring>
using namespace std;
struct mat{
    int matri[3][3];
};
inline mat MatMat(mat a,mat e,int m)
{
    mat t;
    for(int i=0;i<2;++i)
        for(int k=0;k<2;++k)
        {
            t.matri[i][k]=0;    
            for(int j=0;j<2;++j)
            t.matri[i][k]=(t.matri[i][k]+a.matri[i][j]*e.matri[j][k])%m;
        }
    return t;               
}

inline int quick_mod(int q,int m)
{
    mat I,a;

    a.matri[0][0]=0;
    a.matri[1][1]=a.matri[0][1]=a.matri[1][0]=1;

    I.matri[0][0]=I.matri[1][1]=1;
    I.matri[0][1]=I.matri[1][0]=0;

    while (q)
    {
        if(q&1) I=MatMat(a,I,m);
        a=MatMat(a,a,m);    
        q>>=1;  
    } 
    return I.matri[1][1];
} //二分快速幂  

int main()
{
    int m,n;
    while(cin>>n>>m && n!=-1)
    {
        if(n==0 || n==1) {
            cout<<n<<endl;
            continue;
        }
        cout<<quick_mod(n-1,m)<<endl;
    } 
    return 0;
} 

 

posted @ 2013-12-05 21:09  y丫t  阅读(288)  评论(0编辑  收藏  举报