跳到正文

科技·工程

BigInteger2の实现细节

stripe_python约 23 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 23 分钟

版本

  1. v1当前

比较基本的压位就不说了啊……

压位位数 w=9w=9,进制数 b=10w=109b=10^w=10^9。

存储

BigInteger 内部使用一个 long long 类型的指针表示数位的头指针,下标从 11 开始。用 bool 类型的 flag 表示是否大于等于 00。

用指针来手动分配空间,效率一般快于 vector。

扩容

当空间不够时,进行扩容。

令当前容量为 cc,本蒟蒻的扩容策略如下:

  • 当 c<103c < 10^3 时,令 c←2cc \gets 2c;
  • 当 c≥103c \ge 10^3 时,令 c←⌊1.5c⌋c \gets \lfloor 1.5c \rfloor。
C++
inline void BigInteger::push(const digit_t& val) {
	if (capacity == size) {
		long new_capacity = 0;
		if (capacity < 1000) new_capacity = capacity << 1;
		else new_capacity = (new_capacity >> 1) * 3;
		digit_t* new_digits = new digit_t[new_capacity + 1];
		std::memcpy(new_digits, digits, sizeof(long long) * (capacity + 1));
		delete[] digits;
		digits = new_digits, capacity = new_capacity, ++size;
		return;
	}
	digits[++size] = val;
}

由于 BigInteger 的性质,不必要也不应该进行缩容。

C++
inline void BigInteger::pop() {digits[size--] = 0;}

分配空间

比较基本的操作。

C++
inline void BigInteger::reserve(const long& sz) {
	if (digits != nullptr) delete[] digits;
	capacity = sz, size = 0;
	digits = new digit_t[sz + 1];
	std::memset(digits, 0, sizeof(digit_t) * (sz + 1));
}
inline void BigInteger::resize(const long& sz) {
	reserve(sz), size = sz;
}

初始化

long long 类型的初始化很简单,不断除 bb 取余即可:

C++
BigInteger& BigInteger::operator= (const long long& x) {
	flag = (x >= 0);
	reserve(4);
	if (x == 0) return size = 1, digits[1] = 0, *this;
	if (x == LLONG_MIN) return *this = "-9223372036854775808";
	long long n = std::abs(x);
	do {
		push(n % BASE);
		n /= BASE;
	} while (n);
	return *this;
}

注意一处细节:初始化为 LLONG_MIN 时,取绝对值会溢出,需要使用字符串初始化。

字符串初始化的方法是每 ww 位截取一段。std::stoi 是个好东西。

C++
BigInteger& BigInteger::operator= (const std::string& s) {
	flag = true, reserve(s.size() / WIDTH + 1);
	if (s.empty() || s == "-") return *this = 0;
	int i = 0;
	if (s[0] == '-') flag = false, i++;
	for (int j = s.size() - 1; j >= i; j -= WIDTH) {
		int start = std::max(i, j - WIDTH + 1), len = j - start + 1;
		push(std::stoi(s.substr(start, len)));
	}
	return *this;
}

比较操作

写在前面:memcmp 没手写快。

先作特判:

  1. 符号不同,直接返回;
  2. 长度不同,直接返回。

然后逐位比较即可。注意同负情况是反的。

C++
inline int BigInteger::compare(const BigInteger& x) const {
	if (flag && !x.flag) return 1;
	if (!flag && x.flag) return -1;

	int sgn = (flag && x.flag ? 1 : -1);
	if (size > x.size) return sgn;
	if (size < x.size) return -sgn;

	for (int i = size; i >= 1; i--) {
		if (digits[i] > x.digits[i]) return sgn;
		if (digits[i] < x.digits[i]) return -sgn;
	}
	return 0;
}

利用 compare 函数复制粘贴出六种运算符:

C++
bool BigInteger::operator< (const BigInteger& x) const {return compare(x) < 0;}
bool BigInteger::operator> (const BigInteger& x) const {return compare(x) > 0;}
bool BigInteger::operator== (const BigInteger& x) const {return compare(x) == 0;}
bool BigInteger::operator!= (const BigInteger& x) const {return compare(x) != 0;}
bool BigInteger::operator<= (const BigInteger& x) const {return compare(x) <= 0;}
bool BigInteger::operator>= (const BigInteger& x) const {return compare(x) >= 0;}

加法

就是竖式加法,没什么特别的。

C++
BigInteger BigInteger::operator+ (const BigInteger& x) const {
	if (!x.flag) return *this - x.abs();
	if (!flag) return x - abs();

	BigInteger res;
	res.flag = !(flag ^ x.flag);
	int n = std::max(size, x.size) + 1;
	res.reserve(n);
	digit_t carry = 0;
	for (int i = 1; i <= n; i++) {
		digit_t d1 = i <= size ? digits[i] : 0, d2 = i <= x.size ? x.digits[i] : 0;
		res.push(d1 + d2 + carry);
		carry = res.digits[i] / BASE;
		res.digits[i] %= BASE;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();   // 处理前导0
	return res;
}

减法

就是竖式减法,也没什么特别的。

C++
BigInteger BigInteger::operator- (const BigInteger& x) const {
	if (!x.flag) return *this + x.abs();
	if (!flag) return -(abs() + x);
	BigInteger res;
	if (*this < x) res.flag = false;
	digit_t carry = 0;
	int n = std::max(size, x.size);
	res.reserve(n);
	for (int i = 1; i <= n; i++) {
		digit_t d1 = i <= size ? digits[i] : 0, d2 = i <= x.size ? x.digits[i] : 0;
		if (res.flag) res.push(d1 - d2 - carry);
		else res.push(d2 - d1 - carry);
		if (res.digits[i] < 0) res.digits[i] += BASE, carry = 1;
		else carry = 0;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();
	return res;
}

除法 + 取余

用 a mod b=a−⌊ab⌋×ba \bmod b=a-\lfloor \dfrac{a}{b} \rfloor \times b 这种式子求余特别慢。

对于除 22 和高精除单精有一些优化。

C++
BigInteger BigInteger::div2() const {
	BigInteger res = *this;
	for (int i = size; i >= 1; i--) {
		if ((res.digits[i] & 1) && (i > 1)) res.digits[i - 1] += BASE;
		res.digits[i] >>= 1;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();
	return res;
}
BigInteger BigInteger::operator/ (const long long& x) const {
	if (x == 0) throw -1;
	if (*this == 0) return 0;
	if (x == 2) return div2();
	if (x == -2) {BigInteger res = div2(); res.flag = !res.flag; return res;}

	BigInteger res;
	res.flag = !(flag ^ (x >= 0));

	digit_t cur = 0, div = std::abs(x);
	res.resize(size);

	for (int i = size; i >= 1; i--) {
		cur = cur * BASE + digits[i];
		res.digits[i] = res.flag ? (cur / div) : (-cur / -div);
		cur %= div;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();
	return res;
}

倍增除法虽然好写,但是其复杂度是标准的满 O(n2)O(n^2)。考虑试商除法。

朴素的试商效率很低,考虑一个优化。把被除数和除数都乘上一个倍数 tt 使它们位数相等,并且被除数的最高位小于等于除数的最高位。

接下来使用长除法来做,从被除数的高位逐步计算商的每一位。

这样做的除法效率飞快,能达到倍增除法的 1000 倍。

C++
class ZeroDivisionError : public std::exception {
public:
	const char* what() const throw() {return "BigInteger::divmod";}
};

std::pair<BigInteger, BigInteger> BigInteger::divmod(const BigInteger& x) const {
	static const long base = BigInteger::BASE;
	BigInteger a = abs(), b = x.abs();
	if (b == 0) throw ZeroDivisionError();
	if (a < b) return std::make_pair(0, flag ? a : -a);

	long t = base / (x.digits[x.size] + 1);
	a *= t, b *= t;
	long n = a.size, m = b.size;
	BigInteger q = 0, r = 0;
	q.resize(n);
	for (long i = n; i >= 1; i--) {
		r *= base, r += a.digits[i];
		digit_t d1 = m < r.size ? r.digits[m + 1] : 0, d2 = m - 1 < r.size ? r.digits[m] : 0;
		long d = (d1 * base + d2) / b.digits[m];
		r -= b * d;
		while (!r.flag) r += b, d--;
		q.digits[i] = d;
	}
	q.flag = !(flag ^ x.flag), r.flag = flag;
	while (q.size > 1 && q.digits[q.size] == 0) q.pop();
	return std::make_pair(q, r / t);
}

Todo:牛顿迭代 O(nlog⁡n)O(n \log n) 除法。

乘法

终于……最难的东西。

朴素的竖式乘是简单的,复杂度是比较优秀的 O(n2w2)O(\dfrac{n^2}{w^2})。

C++
BigInteger BigInteger::operator* (const BigInteger& x) const {
	BigInteger zero = 0;
	if (*this == zero || x == zero) return zero;
	int n = size, m = x.size;

	BigInteger res;
	res.flag = !(flag ^ x.flag);
	res.resize(n + m + 2);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			res.digits[i + j - 1] += digits[i] * x.digits[j];
			res.digits[i + j] += res.digits[i + j - 1] / BASE;
			res.digits[i + j - 1] %= BASE;
		}
	}
	for (int i = 1; i <= n + m + 1; i++) {
		res.digits[i + 1] += res.digits[i] / BASE;
		res.digits[i] %= BASE;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();
	return res;
}

但是仍然无法应对大数据,需要优化。

考虑 FFT。把两个整数看作 x=10x=10 的两个多项式,求一下卷积,然后处理进位即可。

然后在模板题每个点 950ms 起步。作为一份优秀的高精度模板,此处需要优化。

以下优化参考 https://www.bilibili.com/read/cv23087507/。

压 33 位优化

把多项式的 xx 看作 10310^3,压 33 位处理。精度问题开 long double 可以解决。

__float128 是真的慢。

递归改迭代

就是把 FFT 改成迭代……

三次变两次

很有效的 FFT 技术。把 aa 放在实部,bb 放在虚部,正变换只需要一次即可。

原理:(a+bi)2=a2−b2+2abi(a+bi)^2=a^2-b^2+2abi。

手写 complex

尽管上面文章表示 std::complex<double> 并不满,但实测慢 20ms 左右,为了卡常还是手写。

C++
namespace __FFT {
	constexpr long double PI = 3.14159265358979323846L;

	struct complex {
		long double real, imag;

		complex(long double x = 0.0, long double y = 0.0) : real(x), imag(y) {}

		complex operator+ (const complex& other) const {return complex(real + other.real, imag + other.imag);}
		complex operator- (const complex& other) const {return complex(real - other.real, imag - other.imag);}
		complex operator* (const complex& other) const {return complex(real * other.real - imag * other.imag, real * other.imag + other.real * imag);}
		complex conj() const {return complex(real, -imag);}

		complex& operator+= (const complex& other) {return real += other.real, imag += other.imag, *this;}
		complex& operator-= (const complex& other) {return real -= other.real, imag -= other.imag, *this;}
		complex& operator*= (const complex& other) {return *this = *this * other;}
	};

	complex* arr = nullptr;

	inline void init(int n) {
		if (arr != nullptr) delete[] arr, arr = nullptr;
		arr = new complex[n + 1];
		for (int i = 0; i <= n; i++) arr[i] = complex(0.0, 0.0);
	}

	inline void dft(complex* a, long len) {
		for (long i = len; i >= 2; i >>= 1) {
			complex wn(std::cos(2.0L * PI / i), std::sin(2.0L * PI / i));
			for (long j = 0; j < len; j += i) {
				complex w(1.0, 0.0);
				for (long k = j; k < j + (i >> 1); k++, w *= wn) {
					complex u = a[k], t = a[k + (i >> 1)];
					a[k] = u + t, a[k + (i >> 1)] = w * (u - t);
				}
			}
		}
	}
	inline void idft(complex* a, long len) {
		for (long i = 2; i <= len; i <<= 1) {
			complex wn(std::cos(2.0L * PI / i), std::sin(2.0L * PI / i));
			for (long j = 0; j < len; j += i) {
				complex w(1.0, 0.0);
				for (long k = j; k < j + (i >> 1); k++, w *= wn) {
					complex u = a[k], t = w * a[k + (i >> 1)];
					a[k] = u + t, a[k + (i >> 1)] = u - t;
				}
			}
		}
	}
}

BigInteger BigInteger::fft_mul(const BigInteger& a, const BigInteger& b) {
	long lim = 1;
	while (lim <= 3 * (a.size + b.size)) lim <<= 1;
	__FFT::init(lim);
	using __FFT::arr;
	for (int i = 0; i < a.size; i++) {
		arr[i * 3].real = a.digits[i + 1] % 1000;
		arr[i * 3 + 1].real = a.digits[i + 1] / 1000 % 1000;
		arr[i * 3 + 2].real = a.digits[i + 1] / (1000 * 1000);
	}
	for (int i = 0; i < b.size; i++) {
		arr[i * 3].imag = b.digits[i + 1] % 1000;
		arr[i * 3 + 1].imag = b.digits[i + 1] / 1000 % 1000;
		arr[i * 3 + 2].imag = b.digits[i + 1] / (1000 * 1000);
	}
	dft(arr, lim);
	for (int i = 0; i < lim; i++) arr[i] = (arr[i] * arr[i]).conj();
	idft(arr, lim);
	BigInteger res;
	res.resize(a.size + b.size + 1);
	digit_t carry = 0;
	for (int i = 0; i <= a.size + b.size; i++) {
		carry += (digit_t)(arr[i * 3].imag * -0.5 / lim + 0.5);
		carry += (digit_t)(arr[i * 3 + 1].imag * -0.5 / lim + 0.5) * 1000LL;
		carry += (digit_t)(arr[i * 3 + 2].imag * -0.5 / lim + 0.5) * 1000LL * 1000LL;
		res.digits[i + 1] += carry % BASE, carry /= BASE;
	}
	while (res.size > 1 && res.digits[res.size] == 0) res.pop();
	return res;
}

求幂

就是普通快速幂,没什么特别。

C++
BigInteger BigInteger::pow(const long long& x) const {
	BigInteger res = 1, a = *this;
	for (long long t = x; t != 0; t >>= 1) {
		if (t & 1) res *= a;
		a *= a;
	}
	return res;
}
BigInteger BigInteger::pow(const long long& x, const BigInteger& p) const {
	BigInteger res = 1, a = *this % p;
	for (long long t = x; t != 0; t >>= 1) {
		if (t & 1) res = res * a % p;
		a = a * a % p;
	}
	return res;
}

开根

采用普通二分,使用一个小优化就可以大大缩短时间。

C++
BigInteger BigInteger::sqrt(const long long& x) const {
	BigInteger l = 0, r = *this;
	long long len = size + x - 1;
	while (l + 1 < r) {
		BigInteger mid = (l + r) / 2;
		if (x * mid.size <= len && mid.pow(x) <= *this) l = mid;
		else r = mid;
	}
	return l.pow(x) <= *this ? l : r;
}

GCD

使用优化的辗转相减——Stein 算法。

C++
BigInteger BigInteger::gcd(const BigInteger& x) const {
	BigInteger a = *this, b = x;
	if (a < b) std::swap(a, b);
	if (b == 0) return a;
	int t = 0;
	while (a % 2 == 0 && b % 2 == 0) a = a.div2(), b = b.div2(), t++;
	while (b > 0) {
		if (a % 2 == 0) a = a.div2();
		else if (b % 2 == 0) b = b.div2();
		else a -= b;
		if (a < b) std::swap(a, b);
	}
	while (t--) a += a;
	return a;
}

用辗转相除的复杂度也是对的,可以通过,但比 Stein 慢一倍左右。

LCM 就特别好写了:

C++
BigInteger BigInteger::lcm(const BigInteger& x) const {
	return *this / gcd(x) * x;
}
原文