用C语言编写一个大整数与大整数相乘的小程序。定义两个数组,数组a和数组b,分别存放两个大整数,数组的每一个元素存放四位数,将大整数与大整数的乘积存放数组c中。
时间: 2024-09-23 22:02:53 浏览: 48
大整数乘法C语言版本
在C语言中,由于标准库并不直接支持大整数运算,我们可以使用自定义的数据结构和算法来处理这个问题。下面是一个简单的示例,使用了数组来模拟每一位的乘法和进位过程:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_DIGITS 4
typedef struct {
int digits[MAX_DIGITS];
int size;
} BigInt;
// 初始化大整数
BigInt* initBigInt(int value) {
BigInt* bigInt = malloc(sizeof(BigInt));
bigInt->size = 1;
while (value) {
bigInt->digits[bigInt->size - 1] = value % 10000;
value /= 10000;
bigInt->size++;
}
return bigInt;
}
// 取消初始化
void freeBigInt(BigInt* bigInt) {
free(bigInt);
}
// 相加两个大整数
BigInt* addBigInts(BigInt* a, BigInt* b) {
BigInt* result = malloc(sizeof(BigInt));
result->size = max(a->size, b->size) + 1;
result->digits[0] = 0;
for (int i = 0; i < a->size; i++) {
result->digits[i] += a->digits[i];
if (result->digits[i] >= 10000) {
result->digits[i] -= 10000;
if (i < b->size)
result->digits[i + 1]++;
}
}
for (int i = a->size; i < b->size; i++) {
result->digits[i] += b->digits[i];
if (result->digits[i] >= 10000) {
result->digits[i] -= 10000;
result->digits[i + 1]++;
}
}
return result;
}
// 相乘两个大整数
BigInt* multiplyBigInts(BigInt* a, BigInt* b) {
BigInt* result = initBigInt(0);
for (int i = 0; i < a->size; i++) {
BigInt* temp = initBigInt(0);
for (int j = 0; j < b->size; j++) {
temp = addBigInts(temp, initBigInt(a->digits[i] * b->digits[j]));
}
result = addBigInts(result, temp);
freeBigInt(temp);
}
return result;
}
int main() {
int a[] = {1, 2, 3, 4}; // 1234
int b[] = {5, 6, 7, 8}; // 5678
BigInt* bigA = initBigInt(a[0]);
for (int i = 1; i < 4; i++)
bigA = addBigInts(bigA, initBigInt(a[i]));
BigInt* bigB = initBigInt(b[0]);
for (int i = 1; i < 4; i++)
bigB = addBigInts(bigB, initBigInt(b[i]));
BigInt* product = multiplyBigInts(bigA, bigB);
printf("Product: ");
for (int i = product->size - 1; i >= 0; i--) {
printf("%d", product->digits[i]);
}
printf("\n");
freeBigInt(product);
freeBigInt(bigA);
freeBigInt(bigB);
return 0;
}
阅读全文