将数字向量从基数转换为基数

Converting vector of digits from base to base

本文关键字:转换 数字 向量      更新时间:2023-10-16

如何在不使用 gmp 等库的情况下将基本a中的vector<int>转换为基本b中的vector<int>
包含数字的数字。 ab小于 1024。 a可以小于或大于 b
我考虑过使用标准的基本转换算法,但即使在long long中,这些数字也不适合。

基本上,

您要做的是在基数 a 中实现div/mod b,然后在源编号上重复执行此操作,建立目标数字。 当 b a 时,它有点棘手;您可以使用经典的长除法,或者先隐式地将数字转换为基数 a^k,其中 a^k>= b 并适合 int(简单转换(,然后使用个位数长除法转换为 b。

当然,如果 a == b^k 或 a^k == b(一个基数是另一个基数的整数幂(,则它非常微不足道,因为你根本不需要除法。 很大程度上取决于"a"和"b"是不会改变的实际常量,还是变量。

template<int A, int B> int divmod(std::vector<int> &a) {
    // a is a vector of digits in base A
    // divide a by B in place, returning the remainder
    // implementation left as an exercise for the reader
}
template<int A, int B> std::vector<int> cvtBase(std::vector<int> a) {
    // a is a vector of digits in base A
    // convert it to a vector of digits in base B
    // vectors are in little endian order (least significant digit first)
    std::vector<int> b;
    do {
        b.push_back(divmod<A,B>(a));
    } while (!isZero(a));
    return b;
}

我想过使用标准的基础转换算法,但即使在long long中,这些数字也不适合.

这是正确的(如:"干净"(方法。由于数字不适合本机数字类型,并且您不想使用现有库,因此您基本上需要实现自己的数字类型,或者至少实现转换算法所需的必要运算(加法、除法、模数(。

最简单(尽管不是最有效的(方法是实现经典的长除法算法。