C语言实现超长整数乘法运算
#include <stdio.h>
#include <string.h>
#define MAX_LEN 81
void reverse(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
}
void multiply(char *a, char *b, char *result) {
int len_a = strlen(a);
int len_b = strlen(b);
int len_result = len_a + len_b;
int carry = 0;
memset(result, '0', len_result);
reverse(a);
reverse(b);
for (int i = 0; i < len_a; i++) {
carry = 0;
for (int j = 0; j < len_b; j++) {
int digit = (a[i] - '0') * (b[j] - '0') + (result[i+j] - '0') + carry;
carry = digit / 10;
result[i+j] = digit % 10 + '0';
}
if (carry > 0) {
result[i+len_b] += carry;
}
}
reverse(result);
while (result[0] == '0' && len_result > 1) {
memmove(result, result + 1, len_result - 1);
len_result--;
}
result[len_result] = '\0';
}
int main() {
char a[MAX_LEN];
char b[MAX_LEN];
char result[MAX_LEN * 2];
printf("Enter the first number: ");
scanf("%s", a);
printf("Enter the second number: ");
scanf("%s", b);
multiply(a, b, result);
printf("The result is: %s\n", result);
return 0;
}
代码解析:
reverse(char *str)函数:- 该函数用于将字符串反转,因为我们需要从个位开始进行乘法运算。
multiply(char *a, char *b, char *result)函数:- 该函数实现超长整数的乘法运算。
- 首先,将
a和b反转,方便从个位开始计算。 - 使用两层循环,遍历
a和b的每个数字,进行逐位相乘。 - 将乘积结果累加到
result中,并处理进位。 - 最后,将
result反转,并去除前导零。
main()函数:- 获取用户输入的两个超长整数。
- 调用
multiply()函数进行计算。 - 打印计算结果。
使用方法:
- 将代码保存为
.c文件,例如multiply.c。 - 使用编译器编译代码,例如
gcc multiply.c -o multiply。 - 运行可执行文件,例如
./multiply。
示例:
Enter the first number: 12345678901234567890
Enter the second number: 98765432109876543210
The result is: 12193263111263526907608512890625
注意:
- 该代码仅支持非负整数。
- 最大支持的数字长度为 80 位。
- 可以根据需要修改
MAX_LEN的值。 - 该代码仅作为示例,实际应用中可能需要进行更多优化和测试。
原文地址: https://www.cveoy.top/t/topic/oRp7 著作权归作者所有。请勿转载和采集!