分治法求大整数乘法,给出c语言代码
时间: 2023-05-28 19:05:48 浏览: 112
分治法,大整数乘法
以下是使用分治法求大整数乘法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void multiply(char *a, char *b, char *result) {
int n1 = strlen(a);
int n2 = strlen(b);
if (n1 == 0 || n2 == 0) {
result[0] = '0';
result[1] = '\0';
return;
}
int n = n1 + n2;
int *buffer = calloc(n, sizeof(int));
int i, j;
for (i = n1 - 1; i >= 0; i--) {
for (j = n2 - 1; j >= 0; j--) {
buffer[i + j + 1] += (a[i] - '0') * (b[j] - '0');
}
}
for (i = n - 1; i > 0; i--) {
buffer[i - 1] += buffer[i] / 10;
buffer[i] %= 10;
}
int k = 0;
while (buffer[k] == 0 && k < n - 1) k++;
for (i = k, j = 0; i < n; i++, j++) {
result[j] = buffer[i] + '0';
}
result[j] = '\0';
free(buffer);
}
void karatsuba(char *x, char *y, char *result) {
int n = strlen(x);
if (n == 1) {
int xy = (x[0] - '0') * (y[0] - '0');
sprintf(result, "%d", xy);
return;
}
int m = n / 2;
char *xl = calloc(m + 1, sizeof(char));
char *xr = calloc(n - m + 1, sizeof(char));
char *yl = calloc(m + 1, sizeof(char));
char *yr = calloc(n - m + 1, sizeof(char));
char *p1 = calloc(2 * n + 1, sizeof(char));
char *p2 = calloc(2 * n + 1, sizeof(char));
char *p3 = calloc(2 * n + 1, sizeof(char));
strncpy(xl, x, m);
strncpy(xr, x + m, n - m);
strncpy(yl, y, m);
strncpy(yr, y + m, n - m);
karatsuba(xl, yl, p1);
karatsuba(xr, yr, p2);
char *xl_plus_xr = calloc(n - m + 1, sizeof(char));
char *yl_plus_yr = calloc(n - m + 1, sizeof(char));
char *p4 = calloc(2 * n + 1, sizeof(char));
multiply(xl, "1", xl_plus_xr);
multiply(xr, "1", xl_plus_xr + m);
multiply(yl, "1", yl_plus_yr);
multiply(yr, "1", yl_plus_yr + m);
karatsuba(xl_plus_xr, yl_plus_yr, p4);
for (int i = 0; i < n; i++) {
p4[i] = p4[i] - p1[i] - p2[i];
}
for (int i = 0; i < 2 * m; i++) {
p3[i] = p1[i];
}
for (int i = 0; i < n; i++) {
p3[i + m] += p4[i];
}
for (int i = 0; i < n - m; i++) {
p3[i + n] += p2[i];
}
int i = 0;
while (p3[i] == '0' && i < 2 * n - 1) i++;
strncpy(result, p3 + i, 2 * n - i);
result[2 * n - i] = '\0';
free(xl);
free(xr);
free(yl);
free(yr);
free(p1);
free(p2);
free(p3);
free(xl_plus_xr);
free(yl_plus_yr);
free(p4);
}
int main() {
char a[1000], b[1000], result[2000];
printf("Enter the first number: ");
scanf("%s", a);
printf("Enter the second number: ");
scanf("%s", b);
karatsuba(a, b, result);
printf("Result: %s\n", result);
return 0;
}
```
该代码使用了Karatsuba算法,一种分治法的变种,可以在O(n^log3)的时间内完成大整数乘法。
阅读全文