简体   繁体   中英

Could someone explain me how this matrix exponentiation function works?

#include <bits/stdc++.h>
using namespace std;
//Program to find the nth fib number using matrix exponentation
void multi_mat(int A[3][3], int B[3][3])
{
    int res_mat[3][3];
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            res_mat[i][j] = 0;
            for (int k = 0; k < 3; k++)
            {
                res_mat[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            A[i][j] = res_mat[i][j];
        }
    }
}
int power(int F[3][3], int n)
{
    int M[3][3] = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}};
    if (n == 1)
        return F[0][0] + F[0][1];
    power(F, n / 2);
    multi_mat(F, F);
    if (n % 2 != 0)
        multi_mat(F, M);
    return F[0][0] + F[0][1];
}
int findfib(int n)
{
    int F[3][3] = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}};
    if (n == 0)
        return 0;
    if (n == 1 || n == 2)
        return 1;
    return power(F, n - 2);
}
int main()
{
    int n = 0;
    cin >> n;
    cout << "The fib of the " << n << "th number is : " << findfib(n) << '\n';
    return 0;
}

This is the code for matrix exponentiation. I'm having trouble understanding where does the data get stored when the multi_mat function is invoked. Also when I call the multi_mat function does the matrix res_mat hold the values when it was previously invoked or does it initialize it with some junk value?

where does the data get stored when the multi_mat function is invoked

Initially, it's stored in res_mat :

res_mat[i][j] += A[i][k] * B[k][j];

but some lines later, it's copied to A :

A[i][j] = res_mat[i][j];

So at the end of the execution, the place where the result is stored is the first argument A , which outside the function is called F , as the function was invoked like:

multi_mat(F, F);

does the matrix res_mat hold the values when it was previously invoked or does it initialize it with some junk value?

Yes, it has "junk" values at this point:

int res_mat[3][3];

but, it's later initialized to zeroes when this line executes for each element of the matrix:

res_mat[i][j] = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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