高精度模板
#include <cstring>
#include <iostream>
#include <vector>
struct BigInt {
std::vector<char> v;
BigInt() {
*this = 0;
}
BigInt(int x) {
*this = x;
}
BigInt &operator=(int x) {
v.clear();
do v.push_back(x % 10); while (x /= 10);
return *this;
}
BigInt &operator=(const BigInt &x) {
v.resize(x.v.size());
memcpy(const_cast<char *>(v.data()), x.v.data(),
x.v.size() * sizeof(char));
return *this;
}
};
std::ostream &operator<<(std::ostream &out, const BigInt &x) {
for (int i = x.v.size() - 1; i >= 0; i--) out << (char)(x.v[i]
+ '0');
return out;
}
BigInt operator+(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.clear();
bool flag = false;
for (int i = 0; i < (int)std::max(a.v.size(), b.v.size());
i++) {
int tmp = 0;
if (i < (int)a.v.size()) tmp += a.v[i];
if (i < (int)b.v.size()) tmp += b.v[i];
if (flag) tmp++, flag = false;
if (tmp >= 10) tmp -= 10, flag = true;
result.v.push_back(tmp);
}
if (flag) result.v.push_back(1);
return result;
}
BigInt &operator+=(BigInt &a, const BigInt &b) {
return a = a + b;
}
BigInt operator-(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.clear();
bool flag = false;
for (int i = 0; i < (int)a.v.size(); i++) {
int tmp = a.v[i];
if (i < (int)b.v.size()) tmp -= b.v[i];
if (flag) tmp--, flag = false;
if (tmp < 0) tmp += 10, flag = true;
result.v.push_back(tmp);
}
int size = result.v.size();
while (size > 1 && result.v[size - 1] == 0) size--;
result.v.resize(size);
return result;
}
BigInt operator*(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.resize(a.v.size() + b.v.size());
for (int i = 0; i < (int)a.v.size(); i++) {
for (int j = 0; j < (int)b.v.size(); j++){
result.v[i + j] += a.v[i] * b.v[j];
result.v[i + j + 1] += result.v[i + j] / 10;
result.v[i + j] %= 10;
}
}
int size = result.v.size();
while (size > 1 && result.v[size - 1] == 0) size--;
result.v.resize(size);
return result;
}
转自 Menci 的博客 : https://oi.men.ci/bigint-template/
作者:Dhclient
出处:https://www.cnblogs.com/dhclient/p/16438847.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】