高精度
当c++自带整数类型的最大值不足以满足我们要求时,我们便需要更高精度的数据结构,此时就需要我们自己写一个高精度类进行计算
请保证在自带整数类型不够用时再使用,以获取更高的性能
以下是c++自带的整数类型(从小到大排序):
char,unsigned char
short,unsigned short
int,unsigned int
long,unsigned long
long long,unsigned long long
__int128_t,__uint128_t(只在GCC有效)struct BigInt
{
int num[1000];//储存每位的数组
int len;//位数
int base = 10;//进制(必须是10的n次方(n>0))
BigInt(int x = 0)
{
memset(num, 0, sizeof(num));
len = 1;
for (int i = x; i; i /= base)
{
num[len] = i % base;
len++;
}
len--;
}
void print()
{
for (int i = len; i >= 1; i--)
printf("%d", num[i]);
}
BigInt operator*(const int &b)
{
for (int i = 1; i <= len; i++)
{
num[i] *= b;
num[i + 1] += num[i] / base;
num[i] %= base;
}
while (num[len + 1])
{
len++;
num[len + 1] += num[len] / base;
num[len] %= base;
}
return *this;
}
BigInt operator*(const BigInt &b)
{
BigInt c;
c.len = len + b.len - 1;
for (int i = 1; i <= len; i++)
for (int j = 1; j <= b.len; j++)
{
c.num[i + j - 1] += num[i] * b.num[j];
c.num[i + j] += c.num[i + j - 1] / base;
c.num[i + j - 1] %= base;
}
while (c.num[c.len + 1])
{
c.len++;
c.num[c.len + 1] += c.num[c.len] / base;
c.num[c.len] %= base;
}
return c;
}
BigInt operator+(const BigInt &b)
{
BigInt c;
c.len = max(len, b.len);
for (int i = 1; i <= c.len; i++)
{
c.num[i] += num[i] + b.num[i];
c.num[i + 1] += c.num[i] / base;
c.num[i] %= base;
}
if (c.num[c.len + 1])
c.len++;
return c;
}
BigInt operator+(const int &b)
{
num[1] += b;
for (int i = 1; num[i] >= base; i++)
{
num[i + 1] += num[i] / base;
num[i] %= base;
if (i == len)
len++;
}
return *this;
}
BigInt operator+=(const BigInt &b)
{
*this = *this + b;
return *this;
}
BigInt operator+=(const int &b)
{
*this = *this + b;
return *this;
}
BigInt operator=(const int &b)
{
memset(num, 0, sizeof(num));
len = 1;
for (int i = b; i; i /= base)
{
num[len] = i % base;
len++;
}
len--;
return *this;
}
}