目录
1.大整数类的构造
结构体BigInteger可用于储存高精度非负整数。
#include<vector>
#include<iostream>
#include<string>
#include<cstdio>
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.length() - 1) / WIDTH + 1;
for (int i = 0; i < len; i++) {
int end = str.length() - i * WIDTH;
int start = max(0, end - WIDTH);
sscanf(str.substr(start, end - start).c_str(), "%d", &x);
s.push_back(x);
}
return *this;
}
};
其中,s用来保存大整数的各个部位。例如,若是要表示1234,则s={4,3,2,1}。用vector而非数组保存数字的好处显而易见:不用关心这个整数到底有多大,vector会自动根据情况申请和释放内存。
上面有两个赋值运算符,一个是直接输入数字,另一个是以输入字符串形式的数字 。
static const int BASE=10000000,其作用是声明一个“属于BigInteger”的常数。注意,这个常数不属于任何BigInteger类型的结构体变量,而是属于BigInteger这个“类型”的,因此称为静态成员变量,在声明时需要加static修饰符。
可以给结构体声明一些属于该结构体类型的静态成员变量,方法是加上static修饰符。静态成员变量在结构体外部使用时要写成“结构体名::静态成员变量名”。
知道怎么用就行
关于BigInteger的输入与输出运算符
ostream& operator << (ostream& out, const BigInteger& x) {
out << x.s.back();
for (int i = x.BASE.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;
}
不重要
此外还有大整数类的四则运算和比较运算符
2.四则运算
这是加法运算符的定义
BigInteger operator + (const BigInteger& b) const {
BigInteger c;
c.s.clear();
for (int i = 0, g = 0;; i++) {
if (g == 0 && i >= s.size() && i >= b.s, size()) {
break;
}
int x = g;
if (i < s.size()) {
x += s[i];
}
if (i < b.s.size()) {
x += b.s[i];
}
c.s, push_back(x % BASE);
g = x / BASE;
}
return c;
}
+=运算符的定义
BigInteger operator +=(const BigInteger& b) {
*this = *this + b;
return *this;
}
3.比较运算符
比较运算符的定义
bool operator < (const BigInteger& b)const {
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;//相等
}