跳到正文

科技·工程

压位高精度

huxint约 18 分钟
原文
文章信息与版本

文章信息

发布
2025年1月16日
收录
2025年12月12日
更新
2026年11月1日
篇幅
约 18 分钟

版本

  1. v1当前

C++20

目前只实现了加减法

后续再实现乘除法

因为压位,效率是比普通的高精度快

支持的数更加大

C++
#pragma once
#include <bits/stdc++.h>

/**
 * Todo: mulply and divide
 * author: huxint
 */
template <int width>
    requires (width > 0 and width < 10)
class BigIntegral {
public:
    constexpr BigIntegral() : sign{}, data{} {}

    constexpr BigIntegral(std::integral auto value) : BigIntegral() {
        sign = value < 0 ? value = -value, true : false;
        do {
            data.push_back(value % Base);
        } while (value /= Base);
    }

    constexpr BigIntegral(const std::ranges::range auto &value) : BigIntegral() {
        int value_size = value.size();
        int pos = std::ranges::find_if_not(value, [](char c) {
            return c == '+' or c == '-';
        }) - value.begin();
        sign ^= std::count(value.begin(), value.begin() + pos, '-') & 1;
        data.reserve((value_size - pos + width - 1) / width);
        for (int i = value_size; i > pos; i -= width) {
            std::size_t blocks_value{};
            for (int j = std::max(pos, i - width); j < i; ++ j) {
                blocks_value = 10 * blocks_value + (value[j] & 0X0F);
            }
            data.push_back(blocks_value);
        }
        this -> trim_lead_zero();
    }

    explicit operator bool() const {
        return not is_zero();
    }

    constexpr auto abs() const -> BigIntegral {
        BigIntegral res(*this);
        res.sign = false;
        return res;
    }

    constexpr auto operator -() const -> BigIntegral {
        if (is_zero()) {
            return BigIntegral(*this);
        }
        BigIntegral res(*this);
        res.sign ^= true;
        return res;
    }

    constexpr auto operator +=(const BigIntegral &other) -> BigIntegral & {
        if (sign == other.sign) {
            addition_impl(other);
        } else if (compare_abs(*this, other) >= 0) {
            subtraction_impl(other);
        } else {
            auto _ = other;
            std::swap(*this, _);
            subtraction_impl(_);
        }
        return *this;
    }

    constexpr auto operator -=(const BigIntegral &other) -> BigIntegral & {
        if (sign == other.sign) {
            if (compare_abs(*this, other) >= 0) {
                subtraction_impl(other);
            } else {
                auto _ = other;
                std::swap(*this, _);
                subtraction_impl(_);
                sign ^= true;
            }
        } else {
            addition_impl(other);
        }
        return *this;
    }

    /**
     * https://stackoverflow.com/questions/13166079/move-semantics-and-pass-by-rvalue-reference-in-overloaded-arithmetic
     */
    template< typename Left, typename Right>
        requires (std::is_convertible_v<Left, BigIntegral> and std::is_convertible_v<Right, BigIntegral> and std::is_lvalue_reference_v<Right &&>)
    friend constexpr auto operator + (Left &&lhs, Right &&rhs) -> BigIntegral {
        return BigIntegral(std::forward<Left>(lhs)) += rhs;
    }

    template< typename Left, typename Right>
        requires (std::is_convertible_v<Left, BigIntegral> and std::is_convertible_v<Right, BigIntegral> and std::is_rvalue_reference_v<Right &&>)
    friend constexpr auto operator + (Left &&lhs, Right &&rhs) -> BigIntegral {
        return BigIntegral(std::move(rhs)) += lhs;
    }

    template< typename Left, typename Right>
        requires (std::is_convertible_v<Left, BigIntegral> and std::is_convertible_v<Right, BigIntegral> and std::is_lvalue_reference_v<Right &&>)
    friend constexpr auto operator - (Left &&lhs, Right &&rhs) -> BigIntegral {
        return BigIntegral(std::forward<Left>(lhs)) -= rhs;
    }

    template< typename Left, typename Right>
        requires (std::is_convertible_v<Left, BigIntegral> and std::is_convertible_v<Right, BigIntegral> and std::is_rvalue_reference_v<Right &&>)
    friend constexpr auto operator - (Left &&lhs, Right &&rhs) -> BigIntegral {
        return BigIntegral(std::move(rhs)) -= lhs;
    }

    friend constexpr auto operator <=>(const BigIntegral &lhs, const BigIntegral &rhs) -> std::strong_ordering {
        if (lhs.sign != rhs.sign) {
            return rhs.sign <=> lhs.sign;
        }
        if (lhs.data.size() != rhs.data.size()) {
            if (lhs.sign) {
                return rhs.data.size() <=> lhs.data.size();
            } else {
                return lhs.data.size() <=> rhs.data.size();
            }
        }
        for (auto lhs_it = lhs.data.rbegin(), rhs_it = rhs.data.rbegin(); lhs_it != lhs.data.rend(); ++ lhs_it, ++ rhs_it) {
            if (*lhs_it != *rhs_it) {
                if (lhs.sign) {
                    return *rhs_it <=> *lhs_it;
                } else {
                    return *lhs_it <=> *rhs_it;
                }
            }
        }
        return std::strong_ordering::equal;
    }

    friend constexpr auto operator ==(const BigIntegral &lhs, const BigIntegral &rhs) -> bool {
        return lhs <=> rhs == std::strong_ordering::equal;
    }

    template <typename Istream>
    friend constexpr auto operator >>(Istream &istream, BigIntegral &self) -> Istream & {
        std::string string_integral;
        istream >> string_integral;
        self = std::move(BigIntegral(std::move(string_integral)));
        return istream;
    }

    template <typename Ostream>
    friend constexpr auto operator <<(Ostream &ostream, const BigIntegral &self) -> Ostream & {
        if (self.is_zero()) {
            ostream << 0;
            return ostream;
        }
        if (self.sign) {
            ostream << '-';
        }
        ostream << self.data.back();
        for (const auto &e : self.data | std::ranges::views::reverse | std::ranges::views::drop(1)) {
            if (std::size_t digits = std::upper_bound(pow10_table.begin(), pow10_table.end(), e) - pow10_table.begin() + 1; width > digits) {
                ostream << zeros.substr(0, width - digits);
            }
            ostream << e;
        }
        return ostream;
    }

private:
    bool sign;
    std::vector<int> data;
    static constexpr std::string_view zeros = "000000000";
    static constexpr std::array<int, 9> pow10_table = {
        10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
    };
    static constexpr int Base = pow10_table[width - 1];

    constexpr auto is_zero() const -> bool {
        return data.empty() or (data.size() == 1 and data.back() == 0);
    }

    constexpr auto trim_lead_zero() -> void {
        data.erase(std::find_if(data.rbegin(), data.rend(), [](const auto &x) {
            return x != 0;
        }).base(), data.end());
        if (data.empty()) {
            sign = false;
        }
    }

    constexpr auto compare_abs(const BigIntegral &lhs, const BigIntegral &rhs) const -> std::strong_ordering {
        if (lhs.data.size() != rhs.data.size()) {
            return lhs.data.size() <=> rhs.data.size();
        }
        for (auto lhs_it = lhs.data.rbegin(), rhs_it = rhs.data.rbegin(); lhs_it != lhs.data.rend(); ++ lhs_it, ++ rhs_it) {
            if (*lhs_it != *rhs_it) {
                return *lhs_it <=> *rhs_it;
            }
        }
        return std::strong_ordering::equal;
    }

    constexpr auto addition_impl(const BigIntegral &other) -> void {
        bool carry{};
        std::size_t i = 0;
        std::size_t other_size = other.data.size();
        if (data.size() < other_size) {
            data.resize(other_size, 0);
        }
        for (; i < other_size; ++ i) {
            if (carry = (data[i] += other.data[i] + carry) >= Base) {
                data[i] -= Base;
            }
        }
        for (; carry; ++ i) {
            if (i == data.size()) {
                data.push_back(0U);
            }
            if (carry = (data[i] += carry) >= Base) {
                data[i] -= Base;
            }
        }
    }

    constexpr auto subtraction_impl(const BigIntegral &other) -> void {
        bool carry{};
        auto current = data.data();
        std::size_t other_size = other.data.size();
        for (std::size_t i = 0; i < other_size or carry; ++ i, ++ current) {
            *current -= carry + (i < other_size ? other.data[i] : 0);
            *current += (carry = *current < 0) ? Base : 0;
        }
        this -> trim_lead_zero();
    }
};
using bigint = BigIntegral<9>;// 9个数一位

如何使用: 声明类型为bigint

例如

C++
bigint a, b, c, d = 8;

支持字符容器构造大数

C++
std::string s = "--888888";
bigint a = std::string("+123456789989877777777");
bigint b = std::vector<char>{'-', '5', '8', '9', '0'};
bigint c = std::array<char, 8>{'-', '7', '7', '7', '7', '7', '7', '7'};
bigint d = s;

运行 std::cout << a << "\n" << b << "\n" << c << "\n" << d << "\n"; 上面的输出为:

代码
123456789989877777777
-5890
-7777777
888888

注意不可以

C++
bigint a = "8888";

因为 "8888" 是 const char * 要显式声明为 std::string 或者 std::string_view这种可迭代容器

已经重载了操作运算符

可以直接a + b - c + c + d + c

以及a += b += c -= d

可以直接输出 std::cout << a << ' ' << b;

直接读入 std::cin >> a >> b >> c >> d;

以及比较运算符 a >= b a <= b a == b a > b a < b a != b

原文
抓取于
  1. indulgence_

    沙发!看到第一眼时真的大为震惊,此代码不仅逻辑严密,还有举例说明,tql!orz%%%