跳到正文

算法·理论

举世无双超级 BigInteger 模板

_hud约 25 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v2当前
  2. v1

别人的

由我和 ChatGPT5-thinking 共同完成。

C++
#ifndef BIGINTEGER_H
#define BIGINTEGER_H

#include <bits/stdc++.h>
using namespace std;

namespace bigint {

static const int base = 1000, bdig = 3;

struct FFT {
    using cd = complex<double>;
    static void fft(vector<cd> & a, bool invert) {
        int n = a.size();
        static vector<int> rev;
        static vector<cd> roots{ {0, 0}, {1, 0} };
        if (rev.size() != n) {
            int k = __builtin_ctz(n);
            rev.assign(n,0);
            for (int i = 0; i < n; ++i)
                rev[i] = (rev[i>>1] >> 1) | ((i&1) << (k-1));
        }
        for (int i = 0; i < n; ++i)
            if (i < rev[i]) swap(a[i], a[rev[i]]);
        if (roots.size() < n) {
            int k = __builtin_ctz(roots.size());
            roots.resize(n);
            while ((1<<k) < n) {
                double angle = M_PI / (1<<k);
                for (int i = 1<<(k-1); i < (1<<k); ++i) {
                    roots[2*i] = roots[i];
                    double ang = angle * (2*i+1 - (1<<k));
                    roots[2*i+1] = cd(cos(ang), sin(ang));
                }
                ++k;
            }
        }
        for (int len = 1; len < n; len <<= 1) {
            for (int i = 0; i < n; i += 2*len) {
                for (int j = 0; j < len; ++j) {
                    cd u = a[i+j];
                    cd v = a[i+j+len] * roots[len+j];
                    a[i+j] = u + v;
                    a[i+j+len] = u - v;
                }
            }
        }
        if (invert) {
            reverse(a.begin()+1, a.end());
            for (int i = 0; i < n; ++i) a[i] /= n;
        }
    }

    static vector<long long> mul(const vector<int> &a, const vector<int> &b) {
        int n = a.size(), m = b.size();
        if (!n || !m) return {};
        int need = n + m;
        int sz = 1; while (sz < need) sz <<= 1;
        vector<cd> fa(sz);
        for (int i = 0; i < n; ++i) fa[i].real(a[i]);
        for (int i = 0; i < m; ++i) fa[i].imag(b[i]);
        fft(fa, false);
        vector<cd> fb(sz);
        for (int i = 0; i < sz; ++i) {
            int j = (sz - i) & (sz - 1);
            cd x = (fa[i] + conj(fa[j])) * cd(0.5, 0);
            cd y = (fa[i] - conj(fa[j])) * cd(0, -0.5);
            fb[i] = x * y;
        }
        fft(fb, true);
        vector<long long> res(need);
        for (int i = 0; i < need; ++i) res[i] = llround(fb[i].real());
        return res;
    }
};

class BigInteger {
public:
    vector<int> a;
    int sign;

    BigInteger(): sign(1) {}
    BigInteger(long long v) { *this = v; }
    BigInteger& operator=(long long v) {
        sign = 1; if (v < 0) { sign = -1; v = -v; }
        a.clear();
        while (v) { a.push_back(v % base); v /= base; }
        return *this;
    }
    BigInteger(const string &s) { read(s); }

    void trim() {
        while (!a.empty() && a.back() == 0) a.pop_back();
        if (a.empty()) sign = 1;
    }

    string tostr() const {
        if (a.empty()) return "0";
        stringstream ss;
        if (sign == -1) ss << '-';
        ss << (a.empty() ? 0 : a.back());
        for (int i = a.size() - 2; i >= 0; --i) {
            ss << setw(bdig) << setfill('0') << a[i];
        }
        return ss.str();
    }

    void read(const string &s) {
        sign = 1; a.clear();
        int pos = 0; while (pos < s.size() && isspace(s[pos])) ++pos;
        if (pos < s.size() && (s[pos] == '-' || s[pos] == '+')) { if (s[pos]=='-') sign = -1; ++pos; }
        while (pos < s.size() && s[pos] == '0') ++pos;
        for (int i = s.size() - 1; i >= pos; i -= bdig) {
            int x = 0;
            int l = max(pos, i - bdig + 1);
            for (int j = l; j <= i; ++j) x = x*10 + (s[j]-'0');
            a.push_back(x);
        }
        trim();
    }

    static int ca(const BigInteger &A, const BigInteger &B) {
        if (A.a.size() != B.a.size()) return A.a.size() < B.a.size() ? -1 : 1;
        for (int i = A.a.size() - 1; i >= 0; --i)
            if (A.a[i] != B.a[i]) return A.a[i] < B.a[i] ? -1 : 1;
        return 0;
    }

    friend bool operator < (const BigInteger &x, const BigInteger &y) {
        if (x.sign != y.sign) return x.sign < y.sign;
        int cmp = ca(x,y);
        return x.sign == 1 ? cmp < 0 : cmp > 0;
    }
    friend bool operator == (const BigInteger &x, const BigInteger &y) {
        return x.sign == y.sign && x.a == y.a;
    }
    friend bool operator != (const BigInteger &x, const BigInteger &y) { return !(x==y); }
    friend bool operator > (const BigInteger &x, const BigInteger &y) { return y < x; }
    friend bool operator <= (const BigInteger &x, const BigInteger &y) { return !(x > y); }
    friend bool operator >= (const BigInteger &x, const BigInteger &y) { return !(x < y); }

    BigInteger operator - () const { BigInteger res = *this; if (!res.iz()) res.sign = -res.sign; return res; }
    bool iz() const { return a.empty(); }

    static BigInteger aa(const BigInteger &x, const BigInteger &y) {
        BigInteger res;
        int n = max(x.a.size(), y.a.size());
        res.a.assign(n, 0);
        int carry = 0;
        for (int i = 0; i < n; ++i) {
            int sum = carry;
            if (i < x.a.size()) sum += x.a[i];
            if (i < y.a.size()) sum += y.a[i];
            carry = sum >= base;
            if (carry) sum -= base;
            res.a[i] = sum;
        }
        if (carry) res.a.push_back(carry);
        return res;
    }

    static BigInteger sa(const BigInteger &x, const BigInteger &y) {
        BigInteger res;
        res.a.assign(x.a.size(), 0);
        int carry = 0;
        for (size_t i = 0; i < x.a.size(); ++i) {
            int cur = x.a[i] - carry - (i < y.a.size() ? y.a[i] : 0);
            carry = 0;
            if (cur < 0) { cur += base; carry = 1; }
            res.a[i] = cur;
        }
        res.trim();
        return res;
    }

    friend BigInteger operator + (const BigInteger &x, const BigInteger &y) {
        if (x.sign == y.sign) {
            BigInteger res = aa(x,y);
            res.sign = x.sign;
            return res;
        }
        if (ca(x,y) >= 0) {
            BigInteger res = sa(x,y); res.sign = x.sign; return res;
        } else {
            BigInteger res = sa(y,x); res.sign = y.sign; return res;
        }
    }
    friend BigInteger operator - (const BigInteger &x, const BigInteger &y) {
        if (x.sign != y.sign) {
            BigInteger res = aa(x,y); res.sign = x.sign; return res;
        }
        if (ca(x,y) >= 0) {
            BigInteger res = sa(x,y); res.sign = x.sign; return res;
        } else {
            BigInteger res = sa(y,x); res.sign = -y.sign; return res;
        }
    }

    friend BigInteger operator * (const BigInteger &x, const BigInteger &y) {
        BigInteger res;
        if (x.iz() || y.iz()) return res;
        int n = x.a.size(), m = y.a.size();
        if (min(n,m) < 32) {
            res.a.assign(n+m, 0);
            long long carry;
            for (int i = 0; i < n; ++i) {
                carry = 0;
                for (int j = 0; j < m || carry; ++j) {
                    long long cur = res.a[i+j] + (long long)x.a[i] * (j < m ? y.a[j] : 0) + carry;
                    res.a[i+j] = cur % base;
                    carry = cur / base;
                }
            }
            res.sign = x.sign * y.sign; res.trim(); return res;
        }
        vector<long long> prod = FFT::mul(x.a, y.a);
        res.a.assign(prod.size(), 0);
        long long carry = 0;
        for (size_t i = 0; i < prod.size(); ++i) {
            long long cur = prod[i] + carry;
            long long digit = cur % base;
            if (digit < 0) digit += base;
            res.a[i] = digit;
            carry = (cur - digit) / base;
        }
        while (carry) { res.a.push_back(carry % base); carry /= base; }
        res.sign = x.sign * y.sign; res.trim(); return res;
    }

    static pair<BigInteger, BigInteger> dm(const BigInteger &a1, const BigInteger &b1) {
        if (b1.iz()) throw runtime_error("Division by zero");
        BigInteger a = a1.abs();
        BigInteger b = b1.abs();
        if (ca(a, b) < 0) return {BigInteger(0), a};
        int norm = base / (b.a.back() + 1);
        a = a.am(norm);
        b = b.am(norm);
        BigInteger q; q.a.assign(a.a.size() - b.a.size() + 1, 0);
        BigInteger r; r.a.assign(a.a.begin(), a.a.end());
        for (int i = q.a.size() - 1; i >= 0; --i) {
            long long ri = i + b.a.size() < r.a.size() ? r.a[i + b.a.size()] : 0;
            long long rj = i + b.a.size() - 1 < r.a.size() ? r.a[i + b.a.size() - 1] : 0;
            long long top = ri * base + rj;
            long long d = top / b.a.back();
            if (d >= base) d = base - 1;
            BigInteger bd = b.ms(d);
            if (bd.a.size() + i > r.a.size()) r.a.resize(bd.a.size() + i, 0);
            while (ca(r, sl(bd, i)) < 0) {
                --d;
                bd = b.ms(d);
            }
            bd.a.insert(bd.a.begin(), i, 0);
            r = sa(r, bd);
            q.a[i] = d;
        }
        q.trim();
        BigInteger rem = r.ds(norm).first;
        return {q, rem};
    }

    static BigInteger sl(const BigInteger &x, int blocks) {
        if (x.iz()) return BigInteger(0);
        BigInteger res = x; res.a.insert(res.a.begin(), blocks, 0); return res;
    }

    BigInteger ms(int m) const {
        if (m == 0 || iz()) return BigInteger(0);
        BigInteger res;
        res.sign = sign;
        res.a.assign(a.size()+1,0);
        long long carry = 0;
        for (size_t i = 0; i < a.size(); ++i) {
            long long cur = carry + (long long)a[i] * m;
            res.a[i] = cur % base;
            carry = cur / base;
        }
        if (carry) res.a[a.size()] = carry;
        res.trim(); return res;
    }

    BigInteger am(int m) const {
        BigInteger res = *this;
        if (m == 1) return res;
        long long carry = 0;
        for (size_t i = 0; i < res.a.size(); ++i) {
            long long cur = (long long)res.a[i] * m + carry;
            res.a[i] = cur % base;
            carry = cur / base;
        }
        while (carry) { res.a.push_back(carry % base); carry /= base; }
        res.trim(); return res;
    }

    pair<BigInteger,int> ds(int v) const {
        BigInteger res; res.a.assign(a.size(), 0);
        long long rem = 0;
        for (int i = a.size()-1; i >= 0; --i) {
            long long cur = a[i] + rem * base;
            res.a[i] = cur / v;
            rem = cur % v;
        }
        res.trim(); return {res, rem};
    }

    friend BigInteger operator / (const BigInteger &a, const BigInteger &b) {
        if (b.iz()) throw runtime_error("Division by zero");
        if (a.iz()) return BigInteger(0);
        int sgn = a.sign * b.sign;
        auto dm = BigInteger::dm(a.abs(), b.abs());
        BigInteger q = dm.first; q.sign = sgn; q.trim(); return q;
    }
    friend BigInteger operator % (const BigInteger &a, const BigInteger &b) {
        if (b.iz()) throw runtime_error("Modulo by zero");
        if (a.iz()) return BigInteger(0);
        auto dm = BigInteger::dm(a.abs(), b.abs());
        BigInteger r = dm.second; r.sign = a.sign; r.trim(); return r;
    }

    BigInteger abs() const { BigInteger r = *this; r.sign = 1; return r; }

    BigInteger& operator += (const BigInteger &v) { *this = *this + v; return *this; }
    BigInteger& operator -= (const BigInteger &v) { *this = *this - v; return *this; }
    BigInteger& operator *= (const BigInteger &v) { *this = *this * v; return *this; }
    BigInteger& operator /= (const BigInteger &v) { *this = *this / v; return *this; }
    BigInteger& operator %= (const BigInteger &v) { *this = *this % v; return *this; }

    friend BigInteger gcd(BigInteger a, BigInteger b) {
        while (!b.iz()) {
            BigInteger r = a % b;
            a = b; b = r;
        }
        return a.abs();
    }

    friend BigInteger pow(BigInteger a, long long e) {
        BigInteger res = 1;
        while (e > 0) {
            if (e & 1) res *= a;
            a *= a; e >>= 1;
        }
        return res;
    }

    friend ostream& operator << (ostream &os, const BigInteger &v) { os << v.tostr(); return os; }
    friend istream& operator >> (istream &is, BigInteger &v) { string s; is >> s; v.read(s); return is; }
};

}
#endif

using Big = bigint::BigInteger;
原文