用C语言写出使用分治法解决规模为n*n(在主函数中手动输入大于2小于100)矩阵乘法的代码
时间: 2023-05-31 13:08:10 浏览: 80
好的,以下是使用分治法解决规模为n*n的矩阵乘法的C语言代码:
```
#include <stdio.h>
void matrix_multiply(int n, int A[][n], int B[][n], int C[][n]) {
if (n == 1) {
C[0][0] = A[0][0] * B[0][0];
} else {
int i, j;
int half_size = n / 2;
int A11[half_size][half_size], A12[half_size][half_size], A21[half_size][half_size], A22[half_size][half_size];
int B11[half_size][half_size], B12[half_size][half_size], B21[half_size][half_size], B22[half_size][half_size];
int C11[half_size][half_size], C12[half_size][half_size], C21[half_size][half_size], C22[half_size][half_size];
int P1[half_size][half_size], P2[half_size][half_size], P3[half_size][half_size], P4[half_size][half_size], P5[half_size][half_size], P6[half_size][half_size], P7[half_size][half_size];
int temp1[half_size][half_size], temp2[half_size][half_size];
for (i = 0; i < half_size; i++) {
for (j = 0; j < half_size; j++) {
A11[i][j] = A[i][j];
B11[i][j] = B[i][j];
}
}
for (i = 0; i < half_size; i++) {
for (j = half_size; j < n; j++) {
A12[i][j-half_size] = A[i][j];
B12[i][j-half_size] = B[i][j];
}
}
for (i = half_size; i < n; i++) {
for (j = 0; j < half_size; j++) {
A21[i-half_size][j] = A[i][j];
B21[i-half_size][j] = B[i][j];
}
}
for (i = half_size; i < n; i++) {
for (j = half_size; j < n; j++) {
A22[i-half_size][j-half_size] = A[i][j];
B22[i-half_size][j-half_size] = B[i][j];
}
}
// Calculate seven products
matrix_multiply(half_size, A11, B11, P1);
matrix_multiply(half_size, A12, B21, P2);
matrix_multiply(half_size, A11, B12, P3);
matrix_multiply(half_size, A12, B22, P4);
matrix_multiply(half_size, A21, B11, P5);
matrix_multiply(half_size, A22, B21, P6);
matrix_multiply(half_size, A21, B12, P7);
matrix_multiply(half_size, A22, B22, temp1);
// Combine products to form C matrix
for (i = 0; i < half_size; i++) {
for (j = 0; j < half_size; j++) {
C11[i][j] = P1[i][j] + P2[i][j];
C12[i][j] = P3[i][j] + P4[i][j];
C21[i][j] = P5[i][j] + P6[i][j];
C22[i][j] = P7[i][j] + temp1[i][j];
}
}
// Copy C11, C12, C21, and C22 into C matrix
for (i = 0; i < half_size; i++) {
for (j = 0; j < half_size; j++) {
C[i][j] = C11[i][j];
C[i][j+half_size] = C12[i][j];
C[i+half_size][j] = C21[i][j];
C[i+half_size][j+half_size] = C22[i][j];
}
}
}
}
int main() {
int n, i, j;
printf("Please enter the size of the matrix (n*n, n>2,n<100): ");
scanf("%d", &n);
int A[n][n], B[n][n], C[n][n];
printf("Please enter elements of matrix A: ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &A[i][j]);
}
}
printf("Please enter elements of matrix B: ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &B[i][j]);
}
}
matrix_multiply(n, A, B, C);
printf("Result matrix: \n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
```
阅读全文