AcWing 791. 高精度大整数类(BigInteger) C++模板
原题链接
中等
作者:
fdc99
,
2024-11-17 21:12:25
,
所有人可见
,
阅读 2
食用注意事项
- 减法如果是负数会返回负数的绝对值
- 乘法只有高精乘以低精, 也就是 Biginteger * long long
- 除法只有高精除以低精, 也就是 Biginteger / long long
代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
struct BigInteger {
static const int BASE = 100000000;
static const int WIDTH = 8;
vector<int> s;
BigInteger(long long num = 0) {*this = num;}
BigInteger operator= (long long num) {
s.clear();
do {
s.push_back(num % BASE);
num /= BASE;
} while(num > 0);
return *this;
}
BigInteger operator= (const string& str) {
s.clear();
int x, len = (str.size() - 1) / WIDTH + 1;
for (int i = 0; i < len; i++) {
int end = str.size() - i * WIDTH;
int start = max(0, end - WIDTH);
sscanf(str.substr(start, end-start).c_str(), "%d", x);
s.push_back(x);
}
return *this;
}
BigInteger operator+ (const BigInteger& b) {
BigInteger c;
c.s.clear();
int t = 0;
for (int i = 0; i < s.size() || i < b.s.size(); i ++) {
if (i < s.size()) t += s[i];
if (i < b.s.size()) t += b.s[i];
c.s.push_back(t % BASE);
t /= BASE;
}
if(t) c.s.push_back(t);
return c;
}
bool operator< (const BigInteger& b) {
if(s.size() < b.s.size()) return s.size() < b.s.size();
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] != b.s[i]) return s[i] < b.s[i];
}
return false;
}
BigInteger operator- (const BigInteger& b) {
if (*this < b) {
return sub(b, *this);
} else {
return sub(*this, b);
}
}
// a >= b
BigInteger sub(const BigInteger& a ,const BigInteger& b) {
BigInteger c;
c.s.clear();
for (int t = 0, i = 0; i < a.s.size(); i ++) {
t = a.s[i] - t;
if (i < b.s.size()) t -= b.s[i];
c.s.push_back((t + BASE) % BASE);
if (t < 0) t = 1;
else t = 0;
}
while(c.s.size() > 1 && c.s.back() == 0) c.s.pop_back();
return c;
}
BigInteger operator* (const long long& b) {
BigInteger c;
c.s.clear();
for (int t = 0, i = 0; i < s.size() || t; i ++) {
if (i < s.size()) t += s[i] * b;
c.s.push_back(t % BASE);
t /= BASE;
}
while(c.s.size() > 1 && c.s.back() == 0) c.s.pop_back();
return c;
}
BigInteger operator/ (const int& b) {
BigInteger c;
c.s.clear();
for (int t = 0, i = s.size() - 1; i >= 0; i--) {
t = t * BASE + s[i];
c.s.push_back(t / b);
t %= b;
}
reverse(c.s.begin(), c.s.end());
while(c.s.size() > 1 && c.s.back() == 0) c.s.pop_back();
return c;
}
};
ostream& operator << (ostream &out, const BigInteger& x) {
out << x.s.back();
for (int i = x.s.size() - 2; i >= 0; i --) {
char buf[20];
sprintf(buf, "%08d", x.s[i]);
for(int j = 0; j < strlen(buf); j ++) out << buf[j];
}
return out;
}
istream& operator >> (istream &in, BigInteger& x) {
string s;
if (!(in >> s)) return in;
x = s;
return in;
}
int main()
{
BigInteger a = 1000, b = 2000;
int c = 3;
cout << a + b << endl;
cout << a - b << endl;
cout << a * c << endl;
cout << a / c << endl;
return 0;
}