Fast power and rapid matrix power operation

Fast power matrix and rapid power

(A) Fast Power template (integer fast exponentiation x ^ N)

For chestnuts

11 decimal = 1011 binary number

3^11 = 3^1011 = 3^8 3^2 3^1

int QuickPow(int x,int N)
{
    int res = x;    //res表示当前底数
    int ans = 1;    //ans表示当前值
    whlle(N)
    {
        if(N&1)
        {
            ans = ans * res;
        }
        res = res * res;
        N = N >> 1; 
    }
    return ans;
}

Note understanding of the role of the board in res and ans

(Ii) Fast power matrix (M-th power of the matrix A, A ^ M)

First presented the board

struct Matrix
{
    int m[maxn][maxn];
}ans,res;
//计算矩形乘法的函数,参数是矩阵 A 和矩阵 B 和一个 n(阶数) 
Maxtrix Mul(Maxtrix A, Maxtrix B, int n)
{
    Maxtrix temp;//定义一个临时矩阵,存放A*B的结果
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            temp.m[i][j] = 0;//初始化temp
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            for(int k=1; k<=n; k++)
                temp.m[i][j] += A.m[i][j]*B.m[i][j];
    return temp;
}
void QuickPower(int N, int n)
{
    //对应整数快速幂,矩阵快速幂的 ans 应该初始化为单位矩阵
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
        {
            if(i == j) ans.m[i][j] = 1;
            else ans.m[i][j] = 0;
        }
        while(N)
        {
            if(N&1)
                ans = Mul(res, res);
            res = Mul(res, res);
            N = N >> 1;
        }
}

example

(1) is well known: Fibonacci number recursive formula:. F [n] = F [n-1] + F [n-2] where f [1] = 1, f [2] = 1, seek values ​​F [n]; and

(2) variant F [n] = A F. [. 1-n-] + B . F. [2-n-] where f [1] = 1, f [2] = 1, find F [n] value;

(3) variant F [n] = A F. [. 1-n-] B + F. [2-n-] C. where + f [1] = 1, f [2] = 1, find F [n] value ;

Guess you like

Origin www.cnblogs.com/double-points/p/11486712.html