跳到正文

个人记录

BigInteger 优化方案与具体实现

Xudongning约 11 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月3日
篇幅
约 11 分钟

版本

  1. v1当前

1. 蒙哥马利模乘优化

C++
class BigInteger {
    // ... 现有代码 ...

    // 新增蒙哥马利相关部分
protected:
    struct MontgomeryParams {
        BigInteger N;      // 模数
        BigInteger N_prime; // N' = -N⁻¹ mod R
        BigInteger R;      // R = 2^k > N
        BigInteger R_sq;   // R² mod N
        int k;            // R的二进制位数
    };

    static MontgomeryParams precompute_montgomery_params(const BigInteger& N);
    static BigInteger to_montgomery(const BigInteger& x, const MontgomeryParams& params);
    static BigInteger from_montgomery(const BigInteger& x_mont, const MontgomeryParams& params);
    static BigInteger montgomery_reduce(BigInteger T, const MontgomeryParams& params);
    static BigInteger montgomery_mult(const BigInteger& a, const BigInteger& b, const MontgomeryParams& params);

public:
    BigInteger mod_mul(const BigInteger& x, const BigInteger& mod) const;
    BigInteger mod_pow(const BigInteger& exp, const BigInteger& mod) const;
};

// 预计算蒙哥马利参数
BigInteger::MontgomeryParams BigInteger::precompute_montgomery_params(const BigInteger& N) {
    MontgomeryParams params;
    params.N = N;

    // 选择R = 2^k > N
    params.k = N._digit_len() * 8 * sizeof(digit_t) + 1;
    params.R = BigInteger(1) << params.k;

    // 计算N' = -N⁻¹ mod R (使用扩展欧几里得算法)
    BigInteger R = params.R;
    BigInteger x, y;
    BigInteger g = extended_gcd(N, R, x, y);
    params.N_prime = (-x) % R;

    // 计算R² mod N
    params.R_sq = (params.R * params.R) % N;

    return params;
}

// 转换为蒙哥马利形式
BigInteger BigInteger::to_montgomery(const BigInteger& x, const MontgomeryParams& params) {
    return (x * params.R) % params.N;
}

// 从蒙哥马利形式转换回来
BigInteger BigInteger::from_montgomery(const BigInteger& x_mont, const MontgomeryParams& params) {
    return montgomery_reduce(x_mont, params);
}

// 蒙哥马利约减核心
BigInteger BigInteger::montgomery_reduce(BigInteger T, const MontgomeryParams& params) {
    // m = T * N' mod R
    BigInteger m = (T * params.N_prime) % params.R;

    // t = (T + m * N) / R
    BigInteger t = (T + m * params.N) / params.R;

    if (t >= params.N) {
        return t - params.N;
    } else {
        return t;
    }
}

// 蒙哥马利乘法
BigInteger BigInteger::montgomery_mult(const BigInteger& a, const BigInteger& b,
                                     const MontgomeryParams& params) {
    BigInteger T = a * b;
    return montgomery_reduce(T, params);
}

// 模乘运算
BigInteger BigInteger::mod_mul(const BigInteger& x, const BigInteger& mod) const {
    if (mod == 0) throw ZeroDivisionError();

    MontgomeryParams params = precompute_montgomery_params(mod);

    BigInteger a_mont = to_montgomery(*this, params);
    BigInteger b_mont = to_montgomery(x, params);

    BigInteger res_mont = montgomery_mult(a_mont, b_mont, params);

    return from_montgomery(res_mont, params);
}

// 模幂运算
BigInteger BigInteger::mod_pow(const BigInteger& exp, const BigInteger& mod) const {
    if (mod == 0) throw ZeroDivisionError();
    if (*this == 0 && exp == 0) throw std::invalid_argument("0^0 is undefined");

    MontgomeryParams params = precompute_montgomery_params(mod);

    BigInteger base_mont = to_montgomery(*this % mod, params);
    BigInteger res_mont = to_montgomery(BigInteger(1), params); // 1 in montgomery form

    for (int i = exp.bit_length() - 1; i >= 0; i--) {
        res_mont = montgomery_mult(res_mont, res_mont, params);
        if (exp.test_bit(i)) {
            res_mont = montgomery_mult(res_mont, base_mont, params);
        }
    }

    return from_montgomery(res_mont, params);
}

2. 内存池优化

C++
class BigInteger {
    // ... 现有代码 ...

private:
    static std::vector<digit_t*> memory_pool;
    static constexpr size_t POOL_CHUNK_SIZE = 1024;

    static digit_t* allocate_digits(size_t size);
    static void deallocate_digits(digit_t* ptr, size_t size);

    // 修改现有方法
    inline void push(const digit_t& val) {
        if (size == capacity) {
            int new_capacity = 0;
            if (capacity < 256) new_capacity = capacity << 1;
            else new_capacity = std::pow(capacity + 1, 0.125) * capacity;

            digit_t* new_digits = allocate_digits(new_capacity + 1);
            std::memcpy(new_digits, digits, sizeof(digit_t) * (capacity + 1));
            deallocate_digits(digits, capacity + 1);

            digits = new_digits, capacity = new_capacity;
        }
        digits[++size] = val;
    }
};

// 静态成员初始化
std::vector<digit_t*> BigInteger::memory_pool;

// 内存分配
digit_t* BigInteger::allocate_digits(size_t size) {
    // 尝试从内存池中获取
    for (auto it = memory_pool.begin(); it != memory_pool.end(); ++it) {
        digit_t* block = *it;
        size_t* block_size = reinterpret_cast<size_t*>(block) - 1;
        if (*block_size >= size) {
            memory_pool.erase(it);
            return block;
        }
    }

    // 没有合适块,分配新内存
    size_t* mem = static_cast<size_t*>(::operator new(sizeof(size_t) + size * sizeof(digit_t)));
    *mem = size;
    return reinterpret_cast<digit_t*>(mem + 1);
}

// 内存释放
void BigInteger::deallocate_digits(digit_t* ptr, size_t size) {
    if (ptr == nullptr) return;

    size_t* block_size = reinterpret_cast<size_t*>(ptr) - 1;

    // 如果块足够大,放入内存池供重用
    if (*block_size >= POOL_CHUNK_SIZE) {
        memory_pool.push_back(ptr);
    } else {
        ::operator delete(block_size);
    }
}

// 修改clear方法
void BigInteger::clear() {
    if (digits != nullptr) {
        deallocate_digits(digits, capacity + 1);
        digits = nullptr;
    }
}
原文