POJ-3070 Fibonacci(矩阵快速幂求Fibonacci数列)

POJ 3070
涨姿势

#include
#include
#include

using namespace std;

const int mod = 10000;

struct matrix{
    int n, m;
    int mat[2][2];
    matrix(){
        n = m = 0;
        memset(mat,0,sizeof(mat));
    }
    void print(){
        printf("%d\n", mat[0][1]);
    }
};
matrix operator *(matrix m1,matrix m2)
{
    matrix res;
    res.n = m1.n;
    res.m = m2.m;
    for (int i = 0; i < m1.n; i++)
    {
        for (int j = 0; j < m2.m; j++)
        {
            for (int k = 0; kreturn res;
}
matrix matrix_pow(matrix x,int y){
    matrix res;
    res.n = res.m =2;
    res.mat[0][0] = res.mat[1][1] = 1;
    while(y)
    {
        if (y&1) res = res*x;
        x = x*x;
        y >>= 1;
    }
    return res;
}
int main(){
    int n;
    matrix x;
    x.n = x.m = 2;
    x.mat[0][0] = x.mat[0][1] = x.mat[1][0] = 1;
    x.mat[1][1] = 0;
    while(scanf("%d", &n) && n >= 0){
        if(n == 0) printf("0\n");
        else{
            matrix ans = matrix_pow(x, n);
            ans.print();
        }
    }
    return 0;
}

你可能感兴趣的:(矩阵乘法)