Can anyone please post their code for Fast Matrix Exponentiation (O(logN)) that they actually use (not the ones from some other websites)? I have been trying to code it but it becomes messy and difficult to put to use. It would be great if there are no classes involved in the code.
UPDATE: Following is the code for Matrix Exponentiation provided by @anon69085231:
# define m
void multiply(int a[][m], int b[][m], int dim) {
int c[m][m];
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
int sum = 0;
for (int k = 0; k < dim; k++) {
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
a[i][j] = c[i][j];
}
}
}
void matrixexponentiation(int arr[][m], int dim, int power) {
int I[m][m];
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
if (i == j) {
I[i][j] = 1;
} else {
I[i][j] = 0;
}
}
}
while (power != 1) {
if (power % 2) {
multiply(I, arr, dim);
power--;
} else {
multiply(arr, arr, dim);
power /= 2;
}
}
multiply(arr, I, dim);
}
(The decrement operation on βpowerβ has been corrected and the code has been formatted )