用C语言写strassen矩阵乘法代码
时间: 2023-04-09 07:04:30 浏览: 217
C语言strassen矩阵乘法代码
5星 · 资源好评率100%
我可以回答您的问题。以下是用C语言编写的Strassen矩阵乘法代码:
```c
#include <stdio.h>
void strassen(int n, int A[][n], int B[][n], int C[][n]) {
if (n == 1) {
C[0][0] = A[0][0] * B[0][0];
return;
}
int m = n / 2;
int A11[m][m], A12[m][m], A21[m][m], A22[m][m];
int B11[m][m], B12[m][m], B21[m][m], B22[m][m];
int C11[m][m], C12[m][m], C21[m][m], C22[m][m];
int P1[m][m], P2[m][m], P3[m][m], P4[m][m], P5[m][m], P6[m][m], P7[m][m];
int temp1[m][m], temp2[m][m];
// Divide A and B into 4 submatrices
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
A11[i][j] = A[i][j];
A12[i][j] = A[i][j + m];
A21[i][j] = A[i + m][j];
A22[i][j] = A[i + m][j + m];
B11[i][j] = B[i][j];
B12[i][j] = B[i][j + m];
B21[i][j] = B[i + m][j];
B22[i][j] = B[i + m][j + m];
}
}
// Compute P1, P2, P3, P4, P5, P6, P7
strassen(m, A11, subtract(m, B12, B22, temp1), P1);
strassen(m, add(m, A11, A12, temp1), B22, P2);
strassen(m, add(m, A21, A22, temp1), B11, P3);
strassen(m, A22, subtract(m, B21, B11, temp1), P4);
strassen(m, add(m, A11, A22, temp1), add(m, B11, B22, temp2), P5);
strassen(m, subtract(m, A12, A22, temp1), add(m, B21, B22, temp2), P6);
strassen(m, subtract(m, A11, A21, temp1), add(m, B11, B12, temp2), P7);
// Compute C11, C12, C21, C22
add(m, subtract(m, add(m, P5, P4, temp1), P2, temp2), P6, C11);
add(m, P1, P2, C12);
add(m, P3, P4, C21);
subtract(m, subtract(m, add(m, P5, P1, temp1), P3, temp2), P7, C22);
// Combine C11, C12, C21, C22 into C
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
C[i][j] = C11[i][j];
C[i][j + m] = C12[i][j];
C[i + m][j] = C21[i][j];
C[i + m][j + m] = C22[i][j];
}
}
}
void add(int n, int A[][n], int B[][n], int C[][n]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
void subtract(int n, int A[][n], int B[][n], int C[][n]) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] - B[i][j];
}
}
}
int main() {
int n = 4;
int A[n][n] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int B[n][n] = {{17, 18, 19, 20}, {21, 22, 23, 24}, {25, 26, 27, 28}, {29, 30, 31, 32}};
int C[n][n];
strassen(n, A, B, C);
printf("Result:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
```
希望这个代码能够帮到您!
阅读全文