矩阵与矩阵运算

矩阵运算模板,思路在注释里

#include<stdio.h>
                    //!!初值需修改为所需值!! 
#define N 2

typedef struct _1    //gcc可能会出错 
{                   // 尽量用g++ 
    __int64 mat[N][N];
    int row;//行 
    int col;//列 
}Matrix;

int mod = 19999997;

Matrix Mul(Matrix left,Matrix right);
Matrix Pow(Matrix x,int n);
Matrix MulMod(Matrix left,Matrix right);
Matrix PowMod(Matrix x,int n);

void Show(Matrix x);




Matrix Mul(Matrix left,Matrix right)
{
    int n,i,j,k;
    Matrix res;

    if(left.col != right.row)
        return res;
    else
        n = left.col;

    res.row = left.row;
    res.col = right.col;

    for(i = 0 ; i < left.row ; i++)
    {
        for( j = 0 ; j < right.col; j++)
        {
            res.mat[i][j] = 0;
            for( k = 0 ; k < n ; k++)
            {
                res.mat[i][j] += left.mat[i][k] * right.mat[k][j];
            }
        }
    }

    return res;
} 

Matrix Pow(Matrix x,int n)
{
    int i,j;
    Matrix res ;

    res.row = x.row;
    res.col = x.col;

    for(i = 0 ; i < res.row ;i++)
    {
        for(j = 0 ; j < res.col ; j++)
        {
            res.mat[i][j] = 0;
        }
        res.mat[i][i] = 1;
    }

    while(n)
    {
        if(n&1)//n % 2 == 1 
            res = Mul(res,x);

        x = Mul(x,x);

        n >>= 1;
    }

    return res; 
}

Matrix MulMod(Matrix left,Matrix right)
{
    int n,i,j,k;
    Matrix res;

    if(left.col != right.row)
        return res;
    else
        n = left.col;

    res.row = left.row;
    res.col = right.col;

    for(i = 0 ; i < left.row ; i++)
    {
        for( j = 0 ; j < right.col; j++)
        {
            res.mat[i][j] = 0;
            for( k = 0 ; k < n ; k++)
            {
                res.mat[i][j] += (left.mat[i][k] * right.mat[k][j]) % mod;
            }
            res.mat[i][j] %= mod;
        }
    }

    return res;
} 


Matrix PowMod(Matrix x,int n)
{
    int i,j;
    Matrix res ;

    res.row = x.row;
    res.col = x.col;

    for(i = 0 ; i < res.row ;i++)
    {
        for(j = 0 ; j < res.col ; j++)
        {
            res.mat[i][j] = 0;
        }
        res.mat[i][i] = 1;
    }

    while(n)
    {
        if(n&1)//n % 2 == 1 
            res = MulMod(res,x);

        x = MulMod(x,x);

        n >>= 1;
    }

    return res; 
}

void Show(Matrix x)
{
    int i,j;

    for(i = 0 ; i < x.row ; i++)
    {
        for(j = 0 ; j < x.col ; j++)
        {
            printf("%d    ",x.mat[i][j]);
        }
        printf("\n");
    }
    printf("\n");   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值