简体   繁体   English

如何在C ++中将零一矩阵升为任意幂?

[英]How to raise a zero-one matrix to any power in C++?

I made a zero-one matrix with power 2. However, I want the code to be applied to any power the user enters. 我用2的幂构成了一个零一矩阵。但是,我希望将代码应用于用户输入的任何幂。 I tried several times, but it didn't work. 我尝试了几次,但没有成功。

Here's a part of the code that would concern you. 这是您所关心的部分代码。

Notes: Suppose the user has entered his (n*m) matrix which is "a", as n and m are equals and they are denoted by s. 注意:假设用户输入了他的(n * m)矩阵“ a”,因为n和m等于并且用s表示。

k=0;
for(int j=0; j<s; j++)
    for(int i=0; i<s; i++)
    {
        m[k]=0;

        for(int t=0; t<s; t++)
        m[k]+=a[j][t]*a[t][i];

        k++;
    }

Here is my implementation for matrix exponentiation: 这是矩阵求幂的实现:

struct matrix {
    intt m[K][K];
    matrix() {
        memset (m, 0, sizeof (m));
    }
    matrix operator * (matrix b) {
        matrix c = matrix();
        for (intt i = 0; i < K; i++) {
            for (intt k = 0; k < K; k++) {
                for (intt j = 0; j < K; j++) {
                    c.m[i][j] = (c.m[i][j] + m[i][k] * b.m[k][j]) % MOD;
                }
            }
        }
        return c;
    }
    matrix pow (intt n) {
        if (n <= 0) {
            return matrix();
        }
        if (n == 1) {
            return *this;
        }
        if (n % 2 == 1) {
            return (*this) * pow (n - 1);
        } else {
            matrix X = pow (n / 2);
            return X * X;
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM