add
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
// 递归计算大整数乘积
|
||||
double bigdataride(long x, long y, int n) {
|
||||
x = llabs(x); y = llabs(y);
|
||||
if (n == 1) {
|
||||
return (double)x * y; // 基本情况
|
||||
} else {
|
||||
if (n % 2 == 1) n--; // 处理奇数位
|
||||
long halfPow = (long)pow(10, n / 2);
|
||||
long a = x / halfPow;
|
||||
long b = x % halfPow;
|
||||
long c = y / halfPow;
|
||||
long d = y % halfPow;
|
||||
|
||||
// 递归计算
|
||||
double ac = bigdataride(a, c, n / 2);
|
||||
double bd = bigdataride(b, d, n / 2);
|
||||
long aJb = a + b;
|
||||
long cJd = c + d;
|
||||
double abcd = bigdataride(aJb, cJd, n / 2);
|
||||
// 返回最终结果
|
||||
return ac * pow(10, n) + (abcd - ac - bd) * pow(10, n / 2) + bd;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
long x = 8782346786879887887L;
|
||||
long y = 4524387689998798768L;
|
||||
// 计算数字长度
|
||||
char sx[20];
|
||||
snprintf(sx, sizeof(sx), "%ld", x);
|
||||
int n = strlen(sx);
|
||||
// 计算并输出结果
|
||||
double s = bigdataride(x, y, n);
|
||||
printf("大数相乘的计算结果为:%lf\n", s);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,38 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#define MAX_LEN 1000
|
||||
// 计算两个大整数的乘积
|
||||
void multiply(const char* a, const char* b, char* result) {
|
||||
int lenA = strlen(a), lenB = strlen(b), lenResult = lenA + lenB;
|
||||
int arr[MAX_LEN * 2] = {0};
|
||||
|
||||
// 进行乘法运算
|
||||
for (int i = 0; i < lenA; ++i)
|
||||
for (int j = 0; j < lenB; ++j)
|
||||
arr[i + j] += (a[lenA - i - 1] - '0') * (b[lenB - j - 1] - '0');
|
||||
// 处理进位
|
||||
for (int i = 0; i < lenResult - 1; ++i) {
|
||||
arr[i + 1] += arr[i] / 10;
|
||||
arr[i] %= 10;
|
||||
}
|
||||
// 构建结果字符串
|
||||
int index = 0;
|
||||
while (index < lenResult && arr[index] == 0) ++index;
|
||||
if (index == lenResult) strcpy(result, "0");
|
||||
else {
|
||||
for (int i = index; i < lenResult; ++i)
|
||||
result[i - index] = arr[lenResult - i - 1] + '0';
|
||||
result[lenResult - index] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
char a[MAX_LEN + 1], b[MAX_LEN + 1], result[MAX_LEN * 2 + 1];
|
||||
printf("输入第一个大整数: ");
|
||||
scanf("%s", a);
|
||||
printf("输入第二个大整数: ");
|
||||
scanf("%s", b);
|
||||
multiply(a, b, result);
|
||||
printf("结果: %s\n", result);
|
||||
return 0;
|
||||
}
|
||||
Binary file not shown.
Reference in New Issue
Block a user