//数的快速求幂
public static long fun(long base, int index) {
long ans = 1;
while (index > 0) {
if ((index & 1) == 1) {
ans = base * ans;
}
base = base * base;
index >>= 1;
}
return ans;
}
// 矩阵快速幂
private static long[][] mPow(long[][] matrix, int n) {
int row = matrix.length;
int col = matrix[0].length;
long[][] ans = new long[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (i == j) ans[i][j] = 1;
else ans[i][j] = 0;
}
}
while (n != 0) {
if ((n & 1) == 1) {
ans = mMul(ans, matrix);
}
matrix = mMul(matrix, matrix);
n >>= 1;
}
return ans;
}
// 矩阵乘法
private static long[][] mMul(long[][] a, long[][] b) {
int row = a.length;
int col = b[0].length;
long[][] ans = new long[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < b.length; k++) {
ans[i][j] = ans[i][j] + a[i][k] * b[k][j];
}
}
}
return ans;
}
数与矩阵的快速幂以及矩阵乘法的java实现
最新推荐文章于 2024-08-31 10:44:02 发布