用C语言去编程Karatsuba乘法实现两个大整数相乘
时间: 2024-03-05 22:51:43 浏览: 103
用C语言实现两大数相乘
好的,这是一个非常好的问题!Karatsuba乘法是一种快速的大整数乘法算法,其时间复杂度为O(n^log2(3)),比传统的O(n^2)算法要快得多。下面是一个用C语言实现Karatsuba乘法的示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
// 两个大整数相加
char* add(char* num1, char* num2) {
static char result[MAX_LEN+1];
int len1 = strlen(num1);
int len2 = strlen(num2);
int carry = 0;
int i = len1 - 1;
int j = len2 - 1;
int k = 0;
while (i >= 0 || j >= 0 || carry) {
int x = (i >= 0) ? num1[i] - '0' : 0;
int y = (j >= 0) ? num2[j] - '0' : 0;
int sum = x + y + carry;
result[k++] = (sum % 10) + '0';
carry = sum / 10;
i--; j--;
}
result[k] = '\0';
strrev(result);
return result;
}
// 两个大整数相减
char* subtract(char* num1, char* num2) {
static char result[MAX_LEN+1];
int len1 = strlen(num1);
int len2 = strlen(num2);
int borrow = 0;
int i = len1 - 1;
int j = len2 - 1;
int k = 0;
while (i >= 0 || j >= 0) {
int x = (i >= 0) ? num1[i] - '0' : 0;
int y = (j >= 0) ? num2[j] - '0' : 0;
int diff = x - y - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result[k++] = diff + '0';
i--; j--;
}
while (k > 1 && result[k-1] == '0') k--;
result[k] = '\0';
strrev(result);
return result;
}
// 两个大整数相乘
char* multiply(char* num1, char* num2) {
static char result[MAX_LEN*2+1];
int len1 = strlen(num1);
int len2 = strlen(num2);
if (len1 == 0 || len2 == 0) {
result[0] = '0';
result[1] = '\0';
return result;
}
if (len1 == 1 && len2 == 1) {
int x = num1[0] - '0';
int y = num2[0] - '0';
int z = x * y;
if (z == 0) {
result[0] = '0';
result[1] = '\0';
return result;
}
result[0] = z / 10 + '0';
result[1] = z % 10 + '0';
result[2] = '\0';
return result;
}
int n = (len1 > len2) ? len1 : len2;
if (n % 2 != 0) n++;
char* a = (char*) malloc((n/2+1) * sizeof(char));
char* b = (char*) malloc((n/2+1) * sizeof(char));
char* c = (char*) malloc((n/2+1) * sizeof(char));
char* d = (char*) malloc((n/2+1) * sizeof(char));
strncpy(a, num1, len1-n/2);
a[len1-n/2] = '\0';
strncpy(b, num1+len1-n/2, n/2);
b[n/2] = '\0';
strncpy(c, num2, len2-n/2);
c[len2-n/2] = '\0';
strncpy(d, num2+len2-n/2, n/2);
d[n/2] = '\0';
char* ac = multiply(a, c);
char* bd = multiply(b, d);
char* abcd = multiply(add(a, b), add(c, d));
char* adbc = subtract(subtract(abcd, ac), bd);
char* result1 = (char*) malloc((2*n+1) * sizeof(char));
memset(result1, '0', 2*n);
result1[2*n] = '\0';
strcpy(result1+n, bd);
strcpy(result1+n/2, adbc);
strcpy(result1, ac);
free(a); free(b); free(c); free(d);
free(ac); free(bd); free(abcd); free(adbc);
return result1;
}
int main() {
char num1[MAX_LEN+1], num2[MAX_LEN+1];
printf("Input two numbers:\n");
scanf("%s %s", num1, num2);
char* result = multiply(num1, num2);
printf("%s * %s = %s\n", num1, num2, result);
return 0;
}
```
这个程序使用了递归的方式实现Karatsuba乘法,其中add和subtract函数是用来实现大整数相加和相减的。你可以输入两个大整数,然后运行程序,它将输出它们的乘积。
阅读全文