如何快速计算任何底数的整数对数? 关于powers查找表的注释

问题描述

如何快速计算任意底数而不是仅底数10的整数对数? This question对于以10为底的问题有一个非常有效的解决方案,但我想了解如何将其推广到其他基础。

解决方法

基本知识

可以使用b计算任意数量n log_b(n)的对数底数log(n) / log(b),其中log是任何底数的对数(通常是自然对数) )。 log(b)是一个常数,因此,如果我们可以有效地计算某个底数的对数,那么我们可以有效地计算 any 个底数的对数。

不幸的是,只有当我们不输入数字时,才可以进行这种转换。对于整数,我们只能快速计算底数对数。例如,log_2(10) = 3。这是8到15之间的任何数字的结果,尽管这些数字的小数位数不同。因此,此二进制对数可以帮助我们做出一个很好的猜测,但是我们需要完善这个猜测。

以10为基础

上述问题具有以下解决方案:

constexpr unsigned log2floor(uint64_t x) {
    // implementation for C++17 using clang or gcc
    return x ? 63 - __builtin_clzll(x) : 0;

    // implementation using the new C++20 <bit> header
    return x ? 63 - std::countl_zero(x) : 0;
}

constexpr unsigned log10floor(unsigned x) {
    constexpr unsigned char guesses[32] = {
        0,1,2,3,4,5,6,7,8,9,9
    };
    constexpr uint64_t powers[11] = {
        1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000
    };
    unsigned guess = guesses[log2floor(x)];
    return guess + (x >= powers[guess + 1]);
}

请注意,由于该解决方案实际上并非100%正确,因此我必须进行一些修改。

正如问题中所解释的那样,我们根据可以非常有效地计算出的二进制对数进行猜测,然后在必要时增加猜测。

可以使用以下方法计算猜测表:

index -> log_10(exp(2,index)) = log_10(1 << index)

您可以看到该表首先在索引1上有一个4条目,因为exp(2,4) = 16的底log_101

示例

说我们想知道log_10(15)

  1. 我们计算log_2(15) = 3
  2. 我们查找log_10(exp(2,3)) = log_10(8) = 0。这是我们最初的猜测。
  3. 我们查找exp(10,guess + 1) = exp(10,1) = 10
  4. 15 >= 10,因此我们的猜测太低,因此我们返回guess + 1 = 0 + 1 = 1

任何基础的通用化

要将这种方法推广到任何基础,我们必须在constexpr上下文中计算查找表。要计算猜测表,我们需要对任何基础优先的幼稚对数实现:

template <typename Uint>
constexpr Uint logFloor_naive(Uint val,unsigned base)  {
    Uint result = 0;
    while (val /= base) {
        ++result;
    }
    return result;
}

现在,我们可以计算查询表了:

#include <limits>
#include <array>

template <typename Uint,size_t BASE>
constexpr std::array<uint8_t,std::numeric_limits<Uint>::digits> makeGuessTable()
{
    decltype(makeGuessTable<Uint,BASE>()) result{};
    for (size_t i = 0; i < result.size(); ++i) {
        Uint pow2 = static_cast<Uint>(Uint{1} << i);
        result.data[i] = logFloor_naive(pow2,BASE);
    }
    return result;
}

// The maximum possible exponent for a given base that can still be represented
// by a given integer type.
// Example: maxExp<uint8_t,10> = 2,because 10^2 is representable by an 8-bit unsigned
// integer but 10^3 isn't.
template <typename Uint,unsigned BASE>
constexpr Uint maxExp = logFloor_naive<Uint>(static_cast<Uint>(~Uint{0u}),BASE);

// the size of the table is maxPow<Uint,BASE> + 2 because we need to store the maximum power
// +1 because we need to contain it,we are dealing with a size,not an index
// +1 again because for narrow integers,we access guess+1
template <typename Uint,size_t BASE>
constexpr std::array<uint64_t,maxExp<Uint,BASE> + 2> makePowerTable()
{
    decltype(makePowerTable<Uint,BASE>()) result{};
    uint64_t x = 1;
    for (size_t i = 0; i < result.size(); ++i,x *= BASE) {
        result.data[i] = x;
    }
    return result;
}

请注意,我们需要maxExp模板化常量来确定第二个查询表的大小。最后,我们可以使用查找表来提供最终功能:

// If our base is a power of 2,we can convert between the
// logarithms of different bases without losing any precision.
constexpr bool isPow2or0(uint64_t val) {
    return (val & (val - 1)) == 0;
}

template <size_t BASE = 10,typename Uint>
constexpr Uint logFloor(Uint val) {
    if constexpr (isPow2or0(BASE)) {
        return log2floor(val) / log2floor(BASE);
    }
    else {
        constexpr auto guesses = makeGuessTable<Uint,BASE>();
        constexpr auto powers = makePowerTable<Uint,BASE>();

        uint8_t guess = guesses[log2floor(val)];
        
        // Accessing guess + 1 isn't always safe for 64-bit integers.
        // This is why we need this condition. See below for more details.
        if constexpr (sizeof(Uint) < sizeof(uint64_t)
            || guesses.back() + 2 < powers.size()) {
            return guess + (val >= powers[guess + 1]);
        }
        else {
            return guess + (val / BASE >= powers[guess]);
        }
    }
}

关于powers查找表的注释

我们总是在uint64_t表中使用powers的原因是我们访问guess + 1并且exp(10,guess + 1)并不总是可表示的。例如,如果我们使用8位整数,并且猜测为2,那么exp(10,guess + 1)将是1000,使用8位整数无法表示。

通常,这会导致64位整数出现问题,因为没有可用的较大整数类型。但是也有例外。例如,可表示的最大幂2 exp(2,63)小于exp(10,19),后者是最大可表示幂10。这意味着最高的猜测将是18和{ {1}}是可表示的。因此,我们始终可以安全地访问exp(10,19)

这些异常非常有用,因为在这种情况下我们可以避免整数除法。如上所示,可以通过以下方式检测到此类异常:

powers[guess + 1]