用C语言编写程序:输入两个长度大于10的大整数,用karatsuba乘法实现这两个整数相乘,并验证结果的正确性
时间: 2024-02-23 08:02:03 浏览: 115
C语言编写的大整数乘法
好的,以下是用C语言实现的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100000
void strrev(char* s) {
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
}
void padding(char* s, int len) {
int cur_len = strlen(s);
for (int i = 0; i < len - cur_len; i++) {
strrev(s);
strcat(s, "0");
strrev(s);
}
}
void karatsuba(char* x, char* y, char* result) {
int len = strlen(x);
if (len == 1) {
int xy = (x[0] - '0') * (y[0] - '0');
sprintf(result, "%d", xy);
} else {
int m = len / 2;
char x1[MAX_LEN];
char x2[MAX_LEN];
char y1[MAX_LEN];
char y2[MAX_LEN];
char z0[MAX_LEN];
char z1[MAX_LEN];
char z2[MAX_LEN];
char temp1[MAX_LEN];
char temp2[MAX_LEN];
char temp3[MAX_LEN];
strncpy(x1, x, m);
x1[m] = '\0';
strncpy(x2, x + m, len - m);
x2[len - m] = '\0';
strncpy(y1, y, m);
y1[m] = '\0';
strncpy(y2, y + m, len - m);
y2[len - m] = '\0';
karatsuba(x1, y1, z0);
karatsuba(x2, y2, z2);
int x1x2_len = strlen(x1) + strlen(x2);
int y1y2_len = strlen(y1) + strlen(y2);
padding(x1, x1x2_len);
padding(x2, x1x2_len);
padding(y1, y1y2_len);
padding(y2, y1y2_len);
sprintf(temp1, "%d", atoi(x1) + atoi(x2));
sprintf(temp2, "%d", atoi(y1) + atoi(y2));
karatsuba(temp1, temp2, z1);
sprintf(temp1, "%d", atoi(z1) - atoi(z0) - atoi(z2));
padding(temp1, m);
strcat(z0, temp1);
padding(z0, 2 * m);
strcat(z0, z2);
strcpy(result, z0);
}
}
int main() {
char x[MAX_LEN];
char y[MAX_LEN];
char result[MAX_LEN * 2];
printf("请输入两个长度大于10的大整数:\n");
scanf("%s %s", x, y);
karatsuba(x, y, result);
printf("karatsuba乘法的结果为:%s\n", result);
printf("验证结果的正确性:\n");
long long x_num = atoll(x);
long long y_num = atoll(y);
long long result_num = atoll(result);
if (x_num * y_num == result_num) {
printf("结果正确\n");
} else {
printf("结果错误\n");
}
return 0;
}
```
程序中用到了strrev函数将字符串反转、padding函数将短字符串前面补0、karatsuba函数进行高精度乘法,main函数用于输入两个大整数并进行karatsuba乘法,最后验证结果的正确性。
注意,如果输入的两个大整数长度不足10位,程序可能会出现意料之外的错误,因此需要确保输入的两个大整数长度大于10位。
阅读全文