高精加减乘除用c++写出来
时间: 2023-05-18 15:05:52 浏览: 106
当然可以,以下是一个简单的高精度加减乘除的 C 代码示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
typedef struct {
int len;
int num[MAX_LEN];
} BigInt;
void init(BigInt *a) {
memset(a->num, 0, sizeof(a->num));
a->len = 0;
}
void assign(BigInt *a, char *s) {
init(a);
int len = strlen(s);
for (int i = len - 1, j = 0, k = 1; i >= 0; i--) {
a->num[j] += (s[i] - '0') * k;
if (k == 10000) {
j++;
k = 1;
} else {
k *= 10;
}
}
a->len = len / 4 + 1;
while (a->len > 1 && a->num[a->len - 1] == 0) {
a->len--;
}
}
void print(BigInt *a) {
printf("%d", a->num[a->len - 1]);
for (int i = a->len - 2; i >= 0; i--) {
printf("%04d", a->num[i]);
}
printf("\n");
}
int compare(BigInt *a, BigInt *b) {
if (a->len != b->len) {
return a->len - b->len;
}
for (int i = a->len - 1; i >= 0; i--) {
if (a->num[i] != b->num[i]) {
return a->num[i] - b->num[i];
}
}
return 0;
}
void add(BigInt *a, BigInt *b, BigInt *c) {
init(c);
int carry = 0;
for (int i = 0; i < a->len || i < b->len; i++) {
int sum = a->num[i] + b->num[i] + carry;
c->num[c->len++] = sum % 10000;
carry = sum / 10000;
}
if (carry > 0) {
c->num[c->len++] = carry;
}
}
void sub(BigInt *a, BigInt *b, BigInt *c) {
init(c);
int borrow = 0;
for (int i = 0; i < a->len || i < b->len; i++) {
int diff = a->num[i] - b->num[i] - borrow;
if (diff < 0) {
diff += 10000;
borrow = 1;
} else {
borrow = 0;
}
c->num[c->len++] = diff;
}
while (c->len > 1 && c->num[c->len - 1] == 0) {
c->len--;
}
}
void mul(BigInt *a, BigInt *b, BigInt *c) {
init(c);
for (int i = 0; i < a->len; i++) {
int carry = 0;
for (int j = 0; j < b->len; j++) {
int sum = a->num[i] * b->num[j] + c->num[i + j] + carry;
c->num[i + j] = sum % 10000;
carry = sum / 10000;
}
if (carry > 0) {
c->num[i + b->len] += carry;
}
}
c->len = a->len + b->len;
while (c->len > 1 && c->num[c->len - 1] == 0) {
c->len--;
}
}
void div(BigInt *a, BigInt *b, BigInt *c, BigInt *d) {
init(c);
init(d);
for (int i = a->len - 1; i >= 0; i--) {
d->num[0] = a->num[i];
d->len = 1;
int left = 0, right = 9999, mid;
while (left <= right) {
mid = (left + right) / 2;
BigInt tmp, mul;
init(&tmp);
init(&mul);
tmp.num[0] = mid;
tmp.len = 1;
mul(&tmp, b, &mul);
if (compare(&mul, d) <= 0) {
left = mid + 1;
} else {
right = mid - 1;
}
}
c->num[i] = right;
BigInt tmp, mul, sub;
init(&tmp);
init(&mul);
init(&sub);
tmp.num[0] = right;
tmp.len = 1;
mul(&tmp, b, &mul);
sub(a, &mul, &sub);
assign(a, "");
add(&sub, &tmp, a);
}
while (c->len > 1 && c->num[c->len - 1] == 0) {
c->len--;
}
}
int main() {
BigInt a, b, c, d;
char s1[MAX_LEN], s2[MAX_LEN];
scanf("%s%s", s1, s2);
assign(&a, s1);
assign(&b, s2);
add(&a, &b, &c);
sub(&a, &b, &c);
mul(&a, &b, &c);
div(&a, &b, &c, &d);
print(&c);
print(&d);
return 0;
}
```
这个代码实现了高精度加减乘除四个基本运算,可以处理超过 long long 范围的整数。
阅读全文