[java]代码库
/**
*矩阵计算类
*/
class Matrix{
/*
* 根据字符串解析密钥矩阵
* param key 密钥
* param rank 密钥矩阵的阶
* return 返回密钥矩阵
*/
public static int[][] getKeyMatrix(String key,int rank){
key=key.trim();
String[] akey=key.split(" ");
int key_len=akey.length;
int[][] pk=new int[rank][rank]; //密钥矩阵
for(int i=0;i<key_len;i++){
String num=akey[i];
int row=i/rank,col=i%rank;
pk[row][col]=num.charAt(0)-'0'; //初始化第一位
for(int j=1;j<num.length();j++){
pk[row][col]=pk[row][col]*10+num.charAt(j)-'0';
}
}
return pk;
}
/* 矩阵a、b相乘,返回矩阵c */
public static int[][] Multi(int[][] a,int[][] b){
int row=a.length,
col=b[0].length,
rank=b.length;
int[][] c=new int[row][col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
c[i][j]=0;
for(int k=0;k<rank;k++){
c[i][j]+=a[i][k]*b[k][j];
}
c[i][j]%=modular;
}
}
return c;
}
/*
* 计算行列式的值
* param n 矩阵的阶
* param N 矩阵
*/
public static int Det(int n,int[][] matrix) {
if (n == 1) {
return matrix[0][0];
}
int[][] matrix2 = new int[n - 1][n - 1];
int result = 0;
for (int i = 0; i < n; i++) { // 去除第0行第i列
for (int j = 0; j < n-1; j++) {
for (int p = 0; p < i; p++) { // 上移一行
matrix2[j][p] = matrix[j + 1][p];
}
for (int q = i + 1; q < n; q++) { //右下往左上移
matrix2[j][q - 1] = matrix[j + 1][q];
}
}
result = result + (int) Math.pow(-1, i + 1) * matrix[0][i]
* Det(n - 1, matrix2);
}
return result;
}
/*转置矩阵*/
public static int[][] tranMatrix(int n,int[][] matrix){
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++){
int tmp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=tmp;
}
return matrix;
}
/*代数余子式*/
public static int getAdjunct(int n,int[][] matrix,int r,int c){
int[][] matrix2 = new int[n - 1][n - 1];
int result=0;
for(int i=0;i<r;i++){ //上半部分
for(int j=0;j<c;j++) {
matrix2[i][j]=matrix[i][j];
}
for(int j=c;j<n-1;j++){
matrix2[i][j]=matrix[i][j+1];
}
}
for (int i = r; i < n-1; i++) { //下半部分
for (int p = 0; p < c; p++) {
matrix2[i][p] = matrix[i + 1][p];
}
for (int q = c + 1; q < n; q++) {
matrix2[i][q - 1] = matrix[i + 1][q];
}
}
result=Det(n-1, matrix2); //对matrix2求n-1阶行列式
if((r+c)%2==1) result=-result;
return result;
}
/*
* 矩阵的逆
*
*/
public static int[][] ReverseMatrix(int n,int[][] matrix){
int[][] matrix2=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
matrix2[i][j]=matrix[i][j];
int det=Det(n, matrix);
NumberTheory.extended_gcd(det, modular);
int inverse=NumberTheory.x; //乘法逆元
while(inverse<0)
inverse+=26;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix2[i][j]=(inverse*getAdjunct(n, matrix, j, i))%modular;
while(matrix2[i][j]<0){
matrix2[i][j]+=modular;
}
}
}
return matrix2;
}
private static int modular=26;
}
class NumberTheory {
public static int extended_gcd(int a, int b) {
int ret, tmp;
if (b == 0) {
x = 1;
y = 0;
return a;
}
ret = extended_gcd(b, a % b);
tmp = x;
x = y;
y = tmp - a / b * y;
return ret;
}
public static int x,y;
public final static int modular=26;
}