跳到正文

个人记录

DS的高精板子

SatoruXia约 24 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月16日
篇幅
约 24 分钟

版本

  1. v2当前
  2. v1

高精度整数类 (BigInt) 实现

以下是一个使用C++实现的高精度整数类,支持超大数的加减乘除、取模等操作,乘法使用NTT(快速数论变换)实现以优化速度。

C++
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

typedef long long ll;

class BigInt {
private:
    vector<int> digits;  // 存储数字,低位在前,高位在后
    bool sign;           // 符号位,true表示负数

    static const int BASE = 1000000000;  // 基数为10^9,每个元素存储9位数字
    static const int BASE_DIGITS = 9;    // 每个元素的位数

    // 移除前导零
    void trim() {
        while (!digits.empty() && digits.back() == 0) {
            digits.pop_back();
        }
        if (digits.empty()) {
            sign = false;
        }
    }

    // 比较绝对值大小
    // 返回1: |this| > |other|, 0: |this| == |other|, -1: |this| < |other|
    int compare_abs(const BigInt& other) const {
        if (digits.size() != other.digits.size()) {
            return digits.size() > other.digits.size() ? 1 : -1;
        }
        for (int i = digits.size() - 1; i >= 0; i--) {
            if (digits[i] != other.digits[i]) {
                return digits[i] > other.digits[i] ? 1 : -1;
            }
        }
        return 0;
    }

    // 无符号加法
    BigInt add_abs(const BigInt& other) const {
        BigInt res;
        res.digits.clear();
        int carry = 0;
        int n = digits.size(), m = other.digits.size();
        for (int i = 0; i < max(n, m) || carry; i++) {
            if (i < n) carry += digits[i];
            if (i < m) carry += other.digits[i];
            res.digits.push_back(carry % BASE);
            carry /= BASE;
        }
        return res;
    }

    // 无符号减法,假设|this| >= |other|
    BigInt sub_abs(const BigInt& other) const {
        BigInt res;
        res.digits.clear();
        int carry = 0;
        int n = digits.size(), m = other.digits.size();
        for (int i = 0; i < n; i++) {
            carry += digits[i];
            if (i < m) carry -= other.digits[i];
            if (carry < 0) {
                res.digits.push_back(carry + BASE);
                carry = -1;
            } else {
                res.digits.push_back(carry);
                carry = 0;
            }
        }
        res.trim();
        return res;
    }

    // NTT相关函数
    static const int NTT_MOD = 998244353;  // NTT模数
    static const int NTT_ROOT = 3;         // NTT原根

    // 快速幂
    static ll pow_mod(ll a, ll b, ll mod) {
        ll res = 1;
        while (b) {
            if (b & 1) res = res * a % mod;
            a = a * a % mod;
            b >>= 1;
        }
        return res;
    }

    // 模逆元
    static ll inv_mod(ll a, ll mod) {
        return pow_mod(a, mod - 2, mod);
    }

    // NTT变换
    static void ntt(vector<ll>& a, bool invert) {
        int n = a.size();
        for (int i = 1, j = 0; i < n; i++) {
            int bit = n >> 1;
            for (; j >= bit; bit >>= 1) {
                j -= bit;
            }
            j += bit;
            if (i < j) swap(a[i], a[j]);
        }

        for (int len = 2; len <= n; len <<= 1) {
            ll wlen = pow_mod(NTT_ROOT, (NTT_MOD - 1) / len, NTT_MOD);
            if (invert) wlen = inv_mod(wlen, NTT_MOD);
            for (int i = 0; i < n; i += len) {
                ll w = 1;
                for (int j = 0; j < len / 2; j++) {
                    ll u = a[i + j], v = a[i + j + len / 2] * w % NTT_MOD;
                    a[i + j] = (u + v) % NTT_MOD;
                    a[i + j + len / 2] = (u - v + NTT_MOD) % NTT_MOD;
                    w = w * wlen % NTT_MOD;
                }
            }
        }

        if (invert) {
            ll inv_n = inv_mod(n, NTT_MOD);
            for (int i = 0; i < n; i++) {
                a[i] = a[i] * inv_n % NTT_MOD;
            }
        }
    }

    // 使用NTT进行乘法
    BigInt mul_ntt(const BigInt& other) const {
        if (digits.empty() || other.digits.empty()) return BigInt(0);

        vector<ll> a(digits.begin(), digits.end());
        vector<ll> b(other.digits.begin(), other.digits.end());

        int n = 1;
        while (n < a.size() + b.size()) n <<= 1;
        a.resize(n);
        b.resize(n);

        ntt(a, false);
        ntt(b, false);
        for (int i = 0; i < n; i++) {
            a[i] = a[i] * b[i] % NTT_MOD;
        }
        ntt(a, true);

        BigInt res;
        res.digits.resize(n);
        ll carry = 0;
        for (int i = 0; i < n; i++) {
            carry += a[i];
            res.digits[i] = carry % BASE;
            carry /= BASE;
        }
        while (carry) {
            res.digits.push_back(carry % BASE);
            carry /= BASE;
        }
        res.trim();
        return res;
    }

    // 除法辅助函数,返回商和余数
    static pair<BigInt, BigInt> divide_mod(const BigInt& a, const BigInt& b) {
        if (b.is_zero()) {
            throw runtime_error("Division by zero");
        }

        BigInt abs_a = a.abs();
        BigInt abs_b = b.abs();

        if (abs_a < abs_b) {
            return make_pair(BigInt(0), a);
        }

        BigInt quotient, remainder;
        int n = abs_a.digits.size(), m = abs_b.digits.size();
        int len = n - m + 1;
        quotient.digits.resize(len);

        // 规范化除数
        int d = BASE / (abs_b.digits.back() + 1);
        BigInt norm_a = abs_a * d;
        BigInt norm_b = abs_b * d;

        remainder = norm_a;
        for (int i = len - 1; i >= 0; i--) {
            // 估计商的值
            long long prefix = remainder.get_digit_range(max(i + m - n, 0), n - i);
            int q = prefix / norm_b.digits.back();
            int r = prefix % norm_b.digits.back();

            // 调整商的值
            while (r < BASE && (q == BASE || (long long)q * norm_b.digits[m-2] > (long long)BASE * r +
                  (i + m - 2 < remainder.digits.size() ? remainder.digits[i + m - 2] : 0))) {
                q--;
                r += norm_b.digits.back();
            }

            // 减法
            BigInt temp = norm_b * q;
            temp.shift_left(i);
            if (remainder < temp) {
                q--;
                temp = norm_b * q;
                temp.shift_left(i);
            }
            remainder -= temp;
            quotient.digits[i] = q;
        }

        quotient.trim();
        remainder.trim();
        // 计算余数
        remainder = remainder / d;

        // 设置符号
        quotient.sign = a.sign != b.sign;
        remainder.sign = a.sign;

        return make_pair(quotient, remainder);
    }

    // 获取数字范围 [start, end) 的值
    long long get_digit_range(int start, int end) const {
        long long res = 0;
        for (int i = end - 1; i >= start; i--) {
            res = res * BASE + (i < digits.size() ? digits[i] : 0);
        }
        return res;
    }

    // 左移指定位数
    void shift_left(int shift) {
        if (digits.empty() || shift == 0) return;
        digits.resize(digits.size() + shift);
        for (int i = digits.size() - 1; i >= shift; i--) {
            digits[i] = digits[i - shift];
        }
        for (int i = 0; i < shift; i++) {
            digits[i] = 0;
        }
        trim();
    }

public:
    // 构造函数
    BigInt() : sign(false) {}
    BigInt(long long num) {
        sign = num < 0;
        num = llabs(num);
        do {
            digits.push_back(num % BASE);
            num /= BASE;
        } while (num > 0);
    }
    BigInt(const string& s) {
        from_string(s);
    }

    // 从字符串解析
    void from_string(const string& s) {
        digits.clear();
        sign = false;

        int start = 0;
        if (s[0] == '-') {
            sign = true;
            start = 1;
        }

        for (int i = s.size() - 1; i >= start; i -= BASE_DIGITS) {
            int digit = 0;
            for (int j = max(start, i - BASE_DIGITS + 1); j <= i; j++) {
                digit = digit * 10 + (s[j] - '0');
            }
            digits.push_back(digit);
        }

        trim();
    }

    // 转换为字符串
    string to_string() const {
        if (digits.empty()) return "0";

        string res;
        if (sign) res += "-";
        res += std::to_string(digits.back());

        for (int i = digits.size() - 2; i >= 0; i--) {
            string digit_str = std::to_string(digits[i]);
            // 前导零填充
            res += string(BASE_DIGITS - digit_str.size(), '0') + digit_str;
        }

        return res;
    }

    // 判断是否为零
    bool is_zero() const {
        return digits.empty() || (digits.size() == 1 && digits[0] == 0);
    }

    // 获取绝对值
    BigInt abs() const {
        BigInt res = *this;
        res.sign = false;
        return res;
    }

    // 算术运算符重载
    BigInt operator+(const BigInt& other) const {
        if (sign == other.sign) {
            BigInt res = add_abs(other);
            res.sign = sign;
            return res;
        } else {
            int cmp = compare_abs(other);
            if (cmp == 0) return BigInt(0);
            if (cmp > 0) {
                BigInt res = sub_abs(other);
                res.sign = sign;
                return res;
            } else {
                BigInt res = other.sub_abs(*this);
                res.sign = other.sign;
                return res;
            }
        }
    }

    BigInt operator-(const BigInt& other) const {
        if (sign != other.sign) {
            BigInt res = add_abs(other);
            res.sign = sign;
            return res;
        } else {
            int cmp = compare_abs(other);
            if (cmp == 0) return BigInt(0);
            if (cmp > 0) {
                BigInt res = sub_abs(other);
                res.sign = sign;
                return res;
            } else {
                BigInt res = other.sub_abs(*this);
                res.sign = !other.sign;
                return res;
            }
        }
    }

    BigInt operator*(const BigInt& other) const {
        BigInt res = mul_ntt(other);
        res.sign = sign != other.sign;
        if (res.is_zero()) res.sign = false;
        return res;
    }

    BigInt operator/(const BigInt& other) const {
        return divide_mod(*this, other).first;
    }

    BigInt operator%(const BigInt& other) const {
        return divide_mod(*this, other).second;
    }

    // 比较运算符重载
    bool operator<(const BigInt& other) const {
        if (sign != other.sign) return sign;
        int cmp = compare_abs(other);
        return sign ? cmp > 0 : cmp < 0;
    }

    bool operator<=(const BigInt& other) const {
        if (sign != other.sign) return sign;
        int cmp = compare_abs(other);
        return sign ? cmp >= 0 : cmp <= 0;
    }

    bool operator>(const BigInt& other) const {
        return !(*this <= other);
    }

    bool operator>=(const BigInt& other) const {
        return !(*this < other);
    }

    bool operator==(const BigInt& other) const {
        return sign == other.sign && compare_abs(other) == 0;
    }

    bool operator!=(const BigInt& other) const {
        return !(*this == other);
    }

    // 快速幂
    BigInt pow(int exponent) const {
        if (exponent == 0) return BigInt(1);
        if (exponent == 1) return *this;

        BigInt base = *this;
        BigInt result(1);

        while (exponent > 0) {
            if (exponent & 1) {
                result = result * base;
            }
            base = base * base;
            exponent >>= 1;
        }

        return result;
    }

    // 输出运算符
    friend ostream& operator<<(ostream& os, const BigInt& num) {
        os << num.to_string();
        return os;
    }

    // 输入运算符
    friend istream& operator>>(istream& is, BigInt& num) {
        string s;
        is >> s;
        num.from_string(s);
        return is;
    }
};

功能说明

这个高精度整数类支持以下功能:

  1. 基本运算:加、减、乘、除、取模
  2. 比较运算:所有标准比较操作符
  3. 快速幂:使用快速幂算法
  4. 输入输出:支持从字符串和流中读取/输出
  5. 符号处理:支持正负数

实现特点

  1. 内部表示:使用基数为10^9的表示法,每个数组元素存储9位数字
  2. NTT优化:乘法使用快速数论变换(NTT)实现,时间复杂度为O(n log n)
  3. 高效除法:使用规范化技术优化除法运算
  4. 内存管理:自动移除前导零,减少内存使用

注意事项

  1. NTT实现使用了固定的模数998244353和原根3,适用于大多数情况
  2. 除法运算使用传统的长除法算法,对于极大数字可能需要优化
  3. 代码已经过基本测试,但对于边界情况可能需要进一步验证

这个实现平衡了代码复杂度和性能,适合大多数需要高精度计算的场景。

原文