跳到正文

个人记录

高精度学习笔记

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

文章信息

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

版本

  1. v1当前

高精度模板:

C++
// Int.h
#include <iostream>
#include <vector>
#include <string>

namespace utd {
    class Int {
    private:
        const int BASE = 10000;
        bool sign;
        std::vector<int> num;

        static std::string fitstring(int x) {
            std::string base = std::to_string(x);
            while (base.size() != 4) base = "0" + base;
            return base;
        }

        void clean() {
            while (num.size() > 1 && num.back() == 0) {
                num.pop_back();
            }
            if (num.size() == 1 && num[0] == 0) {
                num.clear();
                sign = false;
            }
        }

    public:
        Int() { this->sign = false, this->num.clear(); }

        Int(int x) { this->construct(std::to_string(x)); }

        Int(const std::string &s) { this->construct(s); }

        [[nodiscard]] std::string format() const &{
            if (num.empty()) return "0";
            std::string res;
            for (int i = num.size() - 1; i >= 0; i--) {
                res += Int::fitstring(num[i]);
            }
            while (res[0] == '0') res = res.substr(1);
            if (sign) res = "-" + res;
            return res;
        }

        explicit operator std::string() const { return this->format(); }

        void construct(std::string s) {
            sign = false, num.clear();
            if (!s.empty() && s[0] == '-') {
                sign = true, s = s.substr(1);
            }
            while (s.size() > 1 && s[0] == '0') { // 避免把 "0" 也删掉
                s = s.substr(1);
            }
            if (s.empty() || s == "0") { // 处理 "0" 的情况
                sign = false;
                return;
            }

            int len = s.length();
            // 从后往前,每4位截取一个子串
            for (int i = len; i > 0; i -= 4) {
                int chunk = 0;
                int start = std::max(0, i - 4);
                // std::stoi 更简单安全
                chunk = std::stoi(s.substr(start, i - start));
                num.push_back(chunk);
            }
        }

        void construct(const bool &_sign, const std::vector<int> &_num) {
            this->num = _num;
            this->sign = _sign;
        }

        void construct(const bool &_sign, const Int &it) {
            this->num = it.num;
            this->sign = _sign;
        }

        friend std::istream &operator>>(std::istream &stream, Int &it) {
            std::string s;
            stream >> s;
            it.construct(s);
            return stream;
        }

        friend std::ostream &operator<<(std::ostream &stream, const Int &it) {
            std::string s = it.format();
            stream << s;
            return stream;
        }

        bool operator<(const Int &it) const &{
            if (it.sign != this->sign) {
                return this->sign;
            }
            if (it.num.size() != this->num.size()) {
                return (this->num.size() < it.num.size()) ^ it.sign;
            }
            for (int i = this->num.size() - 1; i >= 0; i--) {
                if (this->num[i] != it.num[i]) {
                    return (this->num[i] < it.num[i]) ^ it.sign;
                }
            }

            return false;
        }

        bool operator>(const Int &it) const &{ return it < (*this); }

        bool operator<=(const Int &it) const &{ return !(it < (*this)); }

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

        bool operator==(const Int &it) const &{ return !(it < (*this)) && !((*this) < it); }

        bool operator!=(const Int &it) const &{ return (it < (*this)) || ((*this) < it); }

        [[nodiscard]] Int abs() const &{
            Int res(*this);
            res.sign = false;
            return res;
        }

        Int operator+() const &{ return (*this); }

        Int operator-() const &{
            Int res(*this);
            res.sign = !this->sign;
            return res;
        }

        [[nodiscard]] Int add(const Int &it) const &{
            if (this->sign == it.sign) {
                Int res;
                int tmp = 0;
                for (int i = 0; i < std::max(it.num.size(), this->num.size()); i++) {
                    int tmpres = tmp;
                    if (i < it.num.size()) tmpres += it.num[i];
                    if (i < this->num.size()) tmpres += this->num[i];
                    tmp = tmpres / BASE;
                    res.num.emplace_back(tmpres % BASE);
                }
                if (tmp) {
                    res.num.emplace_back(tmp);
                }
                while (!res.num.empty() && res.num.back() == 0) {
                    res.num.pop_back();
                }
                return res;
            }
            return {};
        }

        [[nodiscard]] Int sub(const Int &it) const &{
            if ((*this) > it && this->sign == it.sign && !this->sign) {
                Int res;
                int tmp = 0;
                for (int i = 0; i < this->num.size(); i++) {
                    int tmpres = tmp + this->num[i];
                    if (i < it.num.size()) {
                        tmpres -= it.num[i];
                    }
                    tmp = -(tmpres < 0);
                    tmpres += BASE * (tmpres < 0);
                    res.num.emplace_back(tmpres);
                }
                while (!res.num.empty() && res.num.back() == 0) {
                    res.num.pop_back();
                }
                return res;
            }
            return {};
        }

        Int operator+(const Int &it) const &{
            if (it.sign == this->sign && it.sign == 0) {
                return this->add(it);
            } else if (it.sign == this->sign && it.sign == 1) {
                return -this->abs().add(it.abs());
            } else {
                Int res;
                if (it.abs() >= this->abs()) {
                    res.construct(it.sign, it.abs().sub(this->abs()));
                } else {
                    res.construct(this->sign, this->abs().sub(it.abs()));
                }
                return res;
            }
        }

        Int operator-(const Int &it) const &{ return (*this) + (-it); }

        Int operator*(const Int &it) const &{
            Int res;
            res.num.resize(this->num.size() + it.num.size());
            for (int i = 0; i < this->num.size(); i++) {
                for (int j = 0; j < it.num.size(); j++) {
                    res.num[i + j] += this->num[i] * it.num[j];
                }
            }
            int t = 0;
            for (int &i: res.num) {
                i += t;
                t = i / BASE;
                i %= BASE;
            }
            while (t != 0) {
                res.num.push_back(t % BASE), t /= BASE;
            }
            while (!res.num.empty() && res.num.back() == 0) {
                res.num.pop_back();
            }
            res.sign = it.sign ^ this->sign;
            return res;
        }

        Int &operator=(const Int &it) {
            this->sign = it.sign;
            this->num = it.num;
            return (*this);
        }

        // 这是替换你原有 divide 函数的最终稳健版本
        [[nodiscard]] std::pair<Int, Int> divide(const Int& it) const& {
            // 0. 前置检查 (假设调用者已保证 it.abs() > 0)
            if (this->abs() < it) {
                return { Int(0), *this };
            }

            // 1. 初始化
            Int tmp;
            Int res;
            res.num.assign(this->num.size(), 0);

            // 2. 模拟长除法,从高位到低位
            for (int i = this->num.size() - 1; i >= 0; i--) {
                tmp.num.insert(tmp.num.begin(), 0);
                tmp.num[0] = this->num[i];
                tmp.clean();

                if (tmp < it) {
                    res.num[i] = 0;
                    continue;
                }

                // 3. 【核心优化】在完整且安全的范围内进行二分搜索
                int low = 0, high = BASE - 1, ans = 0;

                // 【已移除】不再进行有风险的上界估算优化

                while (low <= high) {
                    int mid = low + (high - low) / 2;
                    if (mid == 0) {
                        low = mid + 1;
                        continue;
                    }
                    if (it * mid <= tmp) {
                        ans = mid;
                        low = mid + 1;
                    } else {
                        high = mid - 1;
                    }
                }

                // 4. 更新商和余数
                res.num[i] = ans;
                if (ans > 0) {
                    tmp -= it * ans;
                }
            }

            // 5. 清理结果并返回
            res.clean();
            tmp.clean();
            return { res, tmp };
        }

        Int operator/(const Int &it) const &{
            Int absdivide = this->abs().divide(it.abs()).first;
            if (it.sign == this->sign) {
                return absdivide;
            }
            if (it.sign != this->sign) {
                if (this->abs().divide(it.abs()).second == 0) {
                    return -absdivide;
                }
                return -absdivide - 1;
            }
        }

        Int operator%(const Int &it) const &{
            if (it.sign == 0) {
                if (it.sign == this->sign) {
                    return this->divide(it).second;
                }
                if (it.sign != this->sign) {
                    Int r = this->abs().divide(it).second;
                    return ((-r) + it) % it;
                }
            } else {
                if (it.sign == this->sign) {
                    return -this->abs().divide(it.abs()).second;
                }
                if (it.sign != this->sign) {
                    return -this->abs().divide(it.abs()).second;
                }
            }
        }

        Int &operator+=(const Int &it) { return (*this) = (*this) + it; }

        Int &operator-=(const Int &it) { return (*this) = (*this) - it; }

        Int &operator*=(const Int &it) { return (*this) = (*this) * it; }

        Int &operator/=(const Int &it) { return (*this) = (*this) / it; }

        Int &operator%=(const Int &it) { return (*this) = (*this) % it; }

        Int operator++(int) {
            Int res(*this);
            (*this) += 1;
            return res;
        }

        Int operator++() {
            (*this) += 1;
            Int res(*this);
            return res;
        }

        Int operator--(int) {
            Int res(*this);
            (*this) -= 1;
            return res;
        }

        Int operator--() {
            (*this) -= 1;
            Int res(*this);
            return res;
        }

        // 请将此函数添加到你的 Int 类的 public 部分
        Int operator*(int n) const &{
            if (n == 0 || this->num.empty()) return Int(0);
            if (n == 1) return *this;

            Int res;
            // 符号处理
            res.sign = this->sign ^ (n < 0);
            if (n < 0) n = -n;

            long long carry = 0;
            for (size_t i = 0; i < this->num.size() || carry > 0; ++i) {
                if (i < this->num.size()) {
                    carry += (long long) this->num[i] * n;
                }
                res.num.push_back(carry % BASE);
                carry /= BASE;
            }
            res.clean();
            return res;
        }
    };
}

使用:

C++
#include "Int.h" // 导入头文件
utd::Int a, b;
signed main() {
    std::cin >> a >> b; // 输入
    // 四则运算
    std::cout << a << " + " << b << " = " << a + b << "\n";
    std::cout << a << " - " << b << " = " << a - b << "\n";
    std::cout << a << " * " << b << " = " << a * b << "\n";
    std::cout << a << " / " << b << " = " << a / b << "\n";
    std::cout << a << " % " << b << " = " << a % b << "\n";
    // 比较大小
    std::cout << a << " <  " << b << " is " << std::boolalpha << (a <  b) << "\n";
    std::cout << a << " >  " << b << " is " << std::boolalpha << (a >  b) << "\n";
    std::cout << a << " <= " << b << " is " << std::boolalpha << (a <= b) << "\n";
    std::cout << a << " >= " << b << " is " << std::boolalpha << (a >= b) << "\n";
    std::cout << a << " == " << b << " is " << std::boolalpha << (a == b) << "\n";
    std::cout << a << " != " << b << " is " << std::boolalpha << (a != b) << "\n";
    return 0;
}
原文