Fast power matrix and rapid power (to be further supplemented)

Fast power

Computing a ^ b ^, code is as follows:

Fast power Code

int multi(int a,int b)
{
    int ans = 1,base = a;
    while(b!=0)
    {
        if(b&1)
            ans *= base;
        base *= base;
        b>>=1;
    }
    return ans;
}

Fast power matrix

It can quickly find Fibonacci number, here with a problem, for example, Fibonacci POJ - 3070

AC code is as follows:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
 
const int MOD = 10000;
 
struct matrix {     //矩阵 
    int m[2][2];
}ans;
 
matrix base = {1, 1, 1, 0}; 
 
matrix multi(matrix a, matrix b) {  //矩阵相乘,返回一个矩阵 
    matrix tmp;
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) {
            tmp.m[i][j] = 0;
            for(int k = 0;  k < 2; k++)
                tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
        }
    }
    return tmp;
}
 
int matrix_pow(matrix a, int n) {   //矩阵快速幂,矩阵a的n次幂 
    ans.m[0][0] = ans.m[1][1] = 1;  //初始化为单位矩阵 
    ans.m[0][1] = ans.m[1][0] = 0;
    while(n) {
        if(n & 1) ans = multi(ans, a);
        a = multi(a, a);
        n >>= 1;
    }
    return ans.m[0][1];
}
 
int main() {
    int n;
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    while(scanf("%d", &n), n != -1) {
        printf("%d\n", matrix_pow(base, n));
    }
    return 0;
} 

Reference blog: https://blog.csdn.net/alps1992/article/details/42131581
https://blog.csdn.net/u014355480/article/details/44659245

Guess you like

Origin www.cnblogs.com/KeepZ/p/11355371.html