矩阵乘法

作者:yxc
链接:https://www.acwing.com/blog/content/25/
来源:AcWing

1,求斐波那契数列的第 n 项
image.png
#include 
#include 
#include 
#include 
#include 

using namespace std;

const int MOD = 1000000007;

void mul(int a[][2], int b[][2], int c[][2])
{
    int temp[][2] = {{0, 0}, {0, 0}};
    for (int i = 0; i < 2; i ++ )
        for (int j = 0; j < 2; j ++ )
            for (int k = 0; k < 2; k ++ )
            {
                long long x = temp[i][j] + (long long)a[i][k] * b[k][j];
                temp[i][j] = x % MOD;
            }
    for (int i = 0; i < 2; i ++ )
        for (int j = 0; j < 2; j ++ )
            c[i][j] = temp[i][j];
}


int f_final(long long n)
{
    int x[2] = {1, 1};

    int res[][2] = {{1, 0}, {0, 1}};
    int t[][2] = {{1, 1}, {1, 0}};
    long long k = n - 1;
    while (k)
    {
        if (k&1) mul(res, t, res);
        mul(t, t, t);
        k >>= 1;
    }

    int c[2] = {0, 0};
    for (int i = 0; i < 2; i ++ )
        for (int j = 0; j < 2; j ++ )
        {
            long long r = c[i] + (long long)x[j] * res[j][i];
            c[i] = r % MOD;
        }

    return c[0];
}


int main()
{
    long long n ;

    cin >> n;
    cout << f_final(n) << endl;

    return 0;
}
1,求斐波那契数列的 前 n 项 的和
#include
#include

using namespace std;

typedef long long LL;

const int N = 3;

int n , m;

void mul(int c[] ,int a[] , int b[][N])
{
    int tmp[N] = {0};
    for(int i = 0 ; i < N ;i ++ )
        for(int j = 0 ; j < N ; j ++ )
            tmp[i] = (tmp[i] + (LL)a[j] * b[j][i]) % m;
   
   memcpy(c , tmp , sizeof tmp);
}

void mul(int c[][N] , int a[][N] , int b[][N])
{
    int tmp[N][N] = {0};
    for(int i = 0 ; i < N ;i ++ )
        for(int j = 0 ; j < N ; j ++)
            for(int k = 0 ; k < N ; k ++ )
                tmp[i][j] = (tmp[i][j] + (LL)a[i][k] * b[k][j] ) % m;
    
    memcpy(c , tmp , sizeof tmp);
}

int main()
{
    cin >> n >> m;
    
    int f[N] = {1 ,1 ,1}; // f1 : {f1 , f2 , s1}
                                // fn : {fn , f(n + 1) ,  Sn}
   // f(n) * A = f (n+1)
    int A[N][N] = {
        {0 ,1 ,0},
        {1 ,1 ,1},
        {0 ,0 ,1}
    };
    
    n -- ;
    while(n)
    {
        if(n & 1) mul(f ,f ,A); // res = res * a
        mul(A , A , A); // a = a * a
        n >>= 1;
    }
    
    cout << f[2] << endl;
    return 0;
}

你可能感兴趣的:(矩阵乘法)