码迷,mamicode.com
首页 > 其他好文 > 详细

初步 - 矩阵快速幂

时间:2017-09-06 00:28:14      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:mem   for   htm   部分   names   clu   out   www   name   

2017-09-05 22:26:02

writer:pprp

参考:http://www.cnblogs.com/yan-boy/archive/2012/11/29/2795294.html

这位大佬写的很简单易懂

关键代码如下:

while(N)
{
    if(N&1)
        res=res*A;
    n>>=1;
    A=A*A;
}

具体代码:

/*
@theme:矩阵快速幂
@writer:pprp
@begin:21:45
@end:22:25
@declare:
@date:2017/9/5
*/

#include <bits/stdc++.h>

using namespace std;

int N;

struct Matrix
{
    int a[3][3];
} origin,res;


void Init()
{
    for(int i = 0 ; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            origin.a[i][j] = 1;
            cout << origin.a[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
    memset(res.a,0,sizeof(res.a));
    //单位矩阵
    res.a[0][0] =  res.a[1][1] = res.a[2][2] = 1;

}

Matrix multiply(Matrix x, Matrix y)
{
    Matrix tmp;
    memset(tmp.a,0,sizeof(tmp.a));
    for(int i = 0 ; i < 3; i++)
    {
        for(int j = 0 ; j < 3 ; j++)
        {
            for(int k = 0 ; k < 3; k++)
            {
                tmp.a[i][j] += x.a[i][k] * y.a[k][j];
            }
        }
    }
    return tmp;
}

//快速幂关键部分
//n为指数
void calc(int n)
{
    int rec = n;
    while(n)
    {
        if(n & 1)
            res = multiply(res,origin);
        n>>=1;
        origin = multiply(origin,origin);
    }
    cout << rec << "次幂的结果如下:" << endl;
    for(int i = 0 ; i < 3; i++)
    {
        for(int j = 0 ; j < 3; j++)
            cout << res.a[i][j] << " ";
        cout << endl;
    }
}


int main()
{

    while(cin >> N)
    {
        Init();
        calc(N);
    }
    return 0;
}

 

初步 - 矩阵快速幂

标签:mem   for   htm   部分   names   clu   out   www   name   

原文地址:http://www.cnblogs.com/pprp/p/7482327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!