这个只是模板。
const int power = 4; // power = log10(base)
const int base = 10000;
#define MAXL 1001
char a[MAXL], b[MAXL];
struct num {
int l;
int a[MAXL];
num() {
memset(a, 0, sizeof (a));
l = 0;
}
num(const char *s) {
memset(a, 0, sizeof (a));
int len = strlen(s);
l = (len + power - 1) / power;
for (int i = 0, t = 0, j = len - 1, w; i < len; w *= 10, ++i, --j) {
if (i % power == 0) {
w = 1, ++t;
}
a[t] += w * (s[j] - '0');
}
}
num(int r) {
for (l = 0; r > 0; r /= base)
a[++l] = r % base;
}
void add(int k) {
if (k || l) a[++l] = k;
}
void re() {
reverse(a + 1, a + l + 1);
}
void print() {
printf("%d", a[l]);
for (int i = l - 1; i > 0; --i) printf("%0*d", power, a[i]);
}
friend ostream & operator<<(ostream &o, num &n) {
o << n.a[n.l];
for (int i = n.l - 1; i > 0; --i) {
o.width(power);
o << n.a[i];
}
return o;
}
friend istream & operator>>(istream &i, num &n) {
char c[MAXL];
i>>c;
n = num(c);
return i;
}
};
bool operator<(const num &p, const num &q) {
if (p.l < q.l) return true;
if (p.l > q.l) return false;
for (int i = p.l; i > 0; --i) {
if (p.a[i] != q.a[i]) return p.a[i] < q.a[i];
}
return false;
}
bool operator<=(const num &p, const num &q) {
if (p.l < q.l) return true;
if (p.l > q.l) return false;
for (int i = p.l; i > 0; --i) {
if (p.a[i] != q.a[i]) return p.a[i] < q.a[i];
}
return true;
}
bool operator==(const num &p, const num &q) {
if (p.l != q.l) return false;
for (int i = p.l; i > 0; --i) {
if (p.a[i] != q.a[i])
return false;
}
return true;
}
num operator+(const num &p, const num &q) {
num c;
c.l = max(p.l, q.l);
for (int i = 1; i <= c.l; ++i) {
c.a[i] += p.a[i] + q.a[i];
c.a[i + 1] += c.a[i] / base;
c.a[i] %= base;
}
if (c.a[c.l + 1]) ++c.l;
return c;
}
num operator-(const num &p, const num &q) {
num c = p;
for (int i = 1; i <= c.l; ++i) {
c.a[i] -= q.a[i];
if (c.a[i] < 0) {
c.a[i] += base;
--c.a[i + 1];
}
}
while (c.l > 0 && !c.a[c.l]) --c.l;
return c;
}
num operator*(const num &p, const num &q) {
num c;
c.l = p.l + q.l - 1;
for (int i = 1; i <= p.l; ++i)
for (int j = 1; j <= q.l; ++j) {
c.a[i + j - 1] += p.a[i] * q.a[j];
c.a[i + j] += c.a[i + j - 1] / base;
c.a[i + j - 1] %= base;
}
if (c.a[c.l + 1]) ++c.l;
while (c.l > 0 && !c.a[c.l]) --c.l; // if p or q is zero
return c;
}
num operator/(const num &p, const num &q) {
num x, y;
for (int i = p.l; i >= 1; --i) {
y.add(p.a[i]);
y.re();
while (!(y < q))
y = y - q, ++x.a[i];
y.re();
}
x.l = p.l;
while (x.l > 0 && !x.a[x.l]) --x.l;
return x;
}