很少写这东西,昨天下午尝试了一下。本高精度类支持有/无符号大整数加、减、乘、比较,特点是简短。有符号整数采用补码实现。
#include <algorithm>
#include <cstring>
#include <cstdio>
typedef long long ll;
struct BigNumber {
const static int w = 20, base = 1e8, lg = 8;
int x[w];
BigNumber(ll a=0)
{
*this = a;
}
BigNumber(const char s[])
{
*this = s;
}
BigNumber operator=(ll a)
{
for (int i = 0; i < w; ++i, a /= base)
x[i] = a % base;
return *this;
}
BigNumber operator=(const char s[])
{
memset(x, 0, sizeof(x));
int n = strlen(s), j = 0, neg = s[0] == '-';
for (int i = n-1; i >= neg && j < w; i -= lg, ++j)
for (int k = std::max(neg, i-lg+1); k <= i; ++k)
x[j] = x[j]*10 + s[k] - '0';
if (neg)
*this = -*this;
return *this;
}
BigNumber operator+(const BigNumber& b) const
{
BigNumber c;
int f = 0;
for (int i = 0; i < w; ++i)
if (f = (c.x[i] = x[i] + b.x[i] + f) >= base)
c.x[i] -= base;
return c;
}
BigNumber operator+=(const BigNumber& b)
{
return *this = *this + b;
}
BigNumber operator-() const
{
BigNumber c;
for (int i = 0; i < w; ++i)
c.x[i] = base-1-x[i];
return c += BigNumber(1);
}
BigNumber operator-(const BigNumber& b) const
{
return *this + (-b);
}
BigNumber operator-=(const BigNumber& b)
{
return *this = *this - b;
}
BigNumber operator*(const BigNumber& b) const
{
BigNumber c;
for (int i = 0; i < w; ++i)
for (int j = 0, f = 0; j+i < w; ++j) {
ll t = (ll)b.x[i] * x[j] + c.x[j+i] + f;
c.x[j+i] = t % base;
f = t / base;
}
return c;
}
BigNumber operator*=(const BigNumber& b)
{
return *this = *this * b;
}
bool operator<(const BigNumber& b) const
{
return (*this-b).x[w-1];
}
friend BigNumber abs(const BigNumber& a)
{
return a.x[w-1] ? -a : a;
}
void print(bool sgn=false)
{
bool neg = sgn && x[w-1];
BigNumber c = neg ? -*this : *this;
int i = w-1;
while (i && !c.x[i])
--i;
if (neg)
putchar('-');
printf("%d", c.x[i--]);
while (i >= 0)
printf("%0*d", lg, c.x[i--]);
}
};