跳到正文

个人记录

高精度是个坏东西

xiao_a_wang约 26 分钟
原文
文章信息与版本

文章信息

收录
2026年8月7日
更新
2026年8月15日
篇幅
约 26 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
// ---------- 三模数 NTT ----------
// 适用于模数满足 NTT 友好且乘积 > 实际值的场合
namespace NTT {
constexpr long long MOD1 = 469762049;  // 原根 3
constexpr long long MOD2 = 998244353;  // 原根 3
constexpr long long MOD3 = 1004535809; // 原根 3
constexpr long long G = 3;

// 快速幂
inline long long qpow(long long a, long long b, long long mod) {
    long long res = 1;
    for (; b; b >>= 1) {
        if (b & 1)
            res = res * a % mod;
        a = a * a % mod;
    }
    return res;
}

// 蝴蝶变换
void ntt(std::vector<long long> &a, int op, long long mod) {
    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)
            std::swap(a[i], a[j]);
    }
    for (int len = 2; len <= n; len <<= 1) {
        long long wlen = qpow(G, (mod - 1) / len, mod);
        if (op == -1)
            wlen = qpow(wlen, mod - 2, mod);
        for (int i = 0; i < n; i += len) {
            long long w = 1;
            for (int j = 0; j < len / 2; ++j) {
                long long u = a[i + j];
                long long v = a[i + j + len / 2] * w % mod;
                a[i + j] = (u + v) % mod;
                a[i + j + len / 2] = (u - v + mod) % mod;
                w = w * wlen % mod;
            }
        }
    }
    if (op == -1) {
        long long inv_n = qpow(n, mod - 2, mod);
        for (auto &x : a)
            x = x * inv_n % mod;
    }
}

// 三个模数下的卷积,返回真实值(已用中国剩余定理合并)
std::vector<__int128> convolution(const std::vector<long long> &a, const std::vector<long long> &b) {
    int n = 1;
    while (n < (int)(a.size() + b.size()) - 1)
        n <<= 1;
    std::vector<long long> A(n), B(n);
    std::copy(a.begin(), a.end(), A.begin());
    std::copy(b.begin(), b.end(), B.begin());

    auto mult_mod = [&](long long mod) -> std::vector<long long> {
        auto f = A, g = B;
        for (auto &x : f)
            x %= mod;
        for (auto &x : g)
            x %= mod;
        ntt(f, 1, mod);
        ntt(g, 1, mod);
        for (int i = 0; i < n; ++i)
            f[i] = f[i] * g[i] % mod;
        ntt(f, -1, mod);
        return f;
    };

    auto res1 = mult_mod(MOD1);
    auto res2 = mult_mod(MOD2);
    auto res3 = mult_mod(MOD3);

    std::vector<__int128> result(n);
    // 使用 __int128 避免溢出(竞赛环境下通常支持)
    constexpr __int128 M1 = MOD1, M2 = MOD2, M3 = MOD3;
    constexpr __int128 M1M2 = M1 * M2;
    long long inv_m1_m2 = qpow(MOD1, MOD2 - 2, MOD2);                  // MOD1 对 MOD2 的逆
    long long inv_m12_m3 = qpow((MOD1 * MOD2) % MOD3, MOD3 - 2, MOD3); // M1M2 对 MOD3 的逆

    for (int i = 0; i < (int)(a.size() + b.size()) - 1; ++i) {
        long long x1 = res1[i];
        long long x2 = res2[i];
        long long x3 = res3[i];
        // CRT 合并 x1, x2 -> x mod M1M2
        long long t = (x2 - x1) % MOD2;
        if (t < 0)
            t += MOD2;
        t = t * inv_m1_m2 % MOD2;
        __int128 m1t = (__int128)t * MOD1 + x1; // 真实值 mod M1M2
        // 合并 x3
        long long u = (x3 - (long long)(m1t % M3)) % MOD3;
        if (u < 0)
            u += MOD3;
        u = u * inv_m12_m3 % MOD3;
        __int128 val = m1t + (__int128)u * M1M2;
        result[i] = val;
    }
    result.resize(a.size() + b.size() - 1);
    return result;
}
} // namespace NTT

// ---------- 高精度整数类 ----------
class llll {
  public:
    static constexpr long long BASE = 1000000000;
    static constexpr int BASE_DIGITS = 9;

    std::vector<int> digits; // 低位在前
    bool sign;               // true 为正,false 为负

    // 清理前导零
    void trim() {
        while (!digits.empty() && digits.back() == 0)
            digits.pop_back();
        if (digits.empty())
            sign = true; // 零视为正
    }

    // 默认构造函数(值为 0)
    llll() : sign(true) {}

    // 从整数构造
    llll(long long val) {
        if (val < 0) {
            sign = false;
            val = -val;
        } else {
            sign = true;
        }
        do {
            digits.push_back(val % BASE);
            val /= BASE;
        } while (val > 0);
    }

    // 从字符串构造
    explicit llll(const std::string &str) {
        if (str.empty()) {
            *this = llll();
            return;
        }
        int start = 0;
        if (str[0] == '-') {
            sign = false;
            start = 1;
        } else {
            sign = true;
        }
        // 跳过前导零
        while (start < (int)str.size() && str[start] == '0')
            ++start;
        if (start == (int)str.size()) {
            *this = llll(0);
            return;
        }
        std::string num = str.substr(start);
        int len = num.size();
        int cnt = (len + BASE_DIGITS - 1) / BASE_DIGITS;
        digits.resize(cnt);
        for (int i = 0; i < cnt; ++i) {
            int l = std::max(0, len - (i + 1) * BASE_DIGITS);
            int r = len - i * BASE_DIGITS;
            digits[i] = std::stoi(num.substr(l, r - l));
        }
        trim();
    }

    // 转为字符串
    std::string toString() const {
        if (digits.empty())
            return "0";
        std::string result;
        if (!sign)
            result += '-';
        char buffer[BASE_DIGITS + 1];
        sprintf(buffer, "%d", digits.back());
        result += buffer;
        for (int i = (int)digits.size() - 2; i >= 0; --i) {
            sprintf(buffer, "%0*d", BASE_DIGITS, digits[i]);
            result += buffer;
        }
        return result;
    }

    // 取绝对值
    llll abs() const {
        llll res = *this;
        res.sign = true;
        return res;
    }

    // 比较绝对值大小(返回 1 表示 |*this| > |other|,0 等,-1 小)
    int cmpAbs(const llll &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;
    }

    // 比较运算符
    bool operator==(const llll &other) const { return sign == other.sign && digits == other.digits; }
    bool operator!=(const llll &other) const { return !(*this == other); }
    bool operator<(const llll &other) const {
        if (sign != other.sign)
            return sign == false; // 负 < 正
        if (!sign)
            return cmpAbs(other) > 0; // 负负比较,绝对值大的反而小
        return cmpAbs(other) < 0;
    }
    bool operator>(const llll &other) const { return other < *this; }
    bool operator<=(const llll &other) const { return !(other < *this); }
    bool operator>=(const llll &other) const { return !(*this < other); }

    // 高精度加法(绝对值相加)
    llll addAbs(const llll &a, const llll &b) const {
        llll res;
        res.sign = true;
        int carry = 0;
        size_t n = std::max(a.digits.size(), b.digits.size());
        res.digits.resize(n);
        for (size_t i = 0; i < n; ++i) {
            long long sum = carry;
            if (i < a.digits.size())
                sum += a.digits[i];
            if (i < b.digits.size())
                sum += b.digits[i];
            res.digits[i] = sum % BASE;
            carry = sum / BASE;
        }
        if (carry)
            res.digits.push_back(carry);
        return res;
    }

    // 高精度减法(绝对值相减,假定 a >= b)
    llll subAbs(const llll &a, const llll &b) const {
        llll res;
        res.sign = true;
        int borrow = 0;
        res.digits.resize(a.digits.size());
        for (size_t i = 0; i < a.digits.size(); ++i) {
            long long diff = a.digits[i] - borrow;
            if (i < b.digits.size())
                diff -= b.digits[i];
            if (diff < 0) {
                diff += BASE;
                borrow = 1;
            } else {
                borrow = 0;
            }
            res.digits[i] = (int)diff;
        }
        res.trim();
        return res;
    }

    // 加法
    llll operator+(const llll &other) const {
        if (sign == other.sign) {
            llll res = addAbs(*this, other);
            res.sign = sign;
            return res;
        }
        // 异号,转化为绝对值相减
        if (cmpAbs(other) >= 0) {
            llll res = subAbs(*this, other);
            res.sign = sign;
            return res;
        } else {
            llll res = subAbs(other, *this);
            res.sign = other.sign;
            return res;
        }
    }

    // 减法
    llll operator-(const llll &other) const {
        llll neg_other = other;
        neg_other.sign = !neg_other.sign;
        return *this + neg_other;
    }

    // 乘法(使用 NTT 快速卷积)
    llll operator*(const llll &other) const {
        if (digits.empty() || other.digits.empty())
            return llll(0);
        std::vector<long long> a(digits.begin(), digits.end());
        std::vector<long long> b(other.digits.begin(), other.digits.end());
        auto conv = NTT::convolution(a, b);
        // 处理进位
        llll res;
        res.sign = (sign == other.sign);
        __int128 carry = 0;
        for (size_t i = 0; i < conv.size(); ++i) {
            __int128 cur = conv[i] + carry;
            res.digits.push_back(cur % BASE);
            carry = cur / BASE;
        }
        while (carry > 0) {
            res.digits.push_back(carry % BASE);
            carry /= BASE;
        }
        res.trim();
        return res;
    }

    // 绝对值除法与取模(二分试商的长除法)
    // 返回 {商, 余数},均为非负
    std::pair<llll, llll> divmodAbs(const llll &divisor) const {
        if (divisor.digits.empty())
            throw std::runtime_error("Division by zero");
        if (cmpAbs(divisor) < 0)
            return {llll(0), *this};
        // 快速路径:如果除数只有一位
        if (divisor.digits.size() == 1) {
            llll q;
            q.sign = true;
            q.digits.resize(digits.size());
            long long rem = 0;
            long long d = divisor.digits[0];
            for (int i = digits.size() - 1; i >= 0; --i) {
                long long cur = rem * BASE + digits[i];
                q.digits[i] = cur / d;
                rem = cur % d;
            }
            q.trim();
            llll r(rem);
            return {q, r};
        }
        // 一般长除
        llll q;
        q.digits.resize(digits.size() - divisor.digits.size() + 1);
        llll rem;
        rem.digits.assign(digits.end() - divisor.digits.size() + 1, digits.end());
        rem.sign = true;
        rem.trim();
        for (int i = digits.size() - divisor.digits.size(); i >= 0; --i) {
            // 将下一位降到余数最高位
            rem.digits.insert(rem.digits.begin(), digits[i]);
            rem.trim();
            // 二分试商
            int low = 0, high = BASE - 1;
            int best = 0;
            while (low <= high) {
                int mid = (low + high) / 2;
                llll product = divisor * llll(mid);
                int cmp = rem.cmpAbs(product);
                if (cmp >= 0) {
                    best = mid;
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
            q.digits[i] = best;
            rem = rem - divisor * llll(best);
        }
        q.trim();
        rem.trim();
        return {q, rem};
    }

    // 除法
    llll operator/(const llll &other) const {
        auto dm = divmodAbs(other);
        dm.first.sign = (sign == other.sign);
        dm.first.trim();
        return dm.first;
    }

    // 取模(余数符号与被除数相同)
    llll operator%(const llll &other) const {
        auto dm = divmodAbs(other);
        dm.second.sign = sign;
        dm.second.trim();
        return dm.second;
    }

    // 复合赋值
    llll &operator+=(const llll &other) {
        *this = *this + other;
        return *this;
    }
    llll &operator-=(const llll &other) {
        *this = *this - other;
        return *this;
    }
    llll &operator*=(const llll &other) {
        *this = *this * other;
        return *this;
    }
    llll &operator/=(const llll &other) {
        *this = *this / other;
        return *this;
    }
    llll &operator%=(const llll &other) {
        *this = *this % other;
        return *this;
    }

    // 单目负号
    llll operator-() const {
        llll res = *this;
        if (!res.digits.empty())
            res.sign = !res.sign;
        return res;
    }

    // 前置/后置自增自减
    llll &operator++() {
        *this = *this + 1;
        return *this;
    }
    llll operator++(int) {
        llll tmp = *this;
        ++*this;
        return tmp;
    }
    llll &operator--() {
        *this = *this - 1;
        return *this;
    }
    llll operator--(int) {
        llll tmp = *this;
        --*this;
        return tmp;
    }
};

// 输入输出流
std::ostream &operator<<(std::ostream &os, const llll &num) {
    os << num.toString();
    return os;
}

std::istream &operator>>(std::istream &is, llll &num) {
    std::string s;
    is >> s;
    num = llll(s);
    return is;
}
原文