Compute fast log base 2 ceiling

前端 未结 14 583
栀梦
栀梦 2020-11-28 11:35

What is a fast way to compute the (long int) ceiling(log_2(i)), where the input and output are 64-bit integers? Solutions for signed or unsigned integers are ac

相关标签:
14条回答
  • 2020-11-28 12:36

    The true fastest solution:

    A binary search tree of 63 entries. These are the powers of 2 from 0 to 63. One-time generation function to create the tree. The leafs represent the log base 2 of the powers (basically, the numbers 1-63).

    To find the answer, you feed a number into the tree, and navigate to the leaf node greater than the item. If the leaf node is exactly equal, result is the leaf value. Otherwise, result is the leaf value + 1.

    Complexity is fixed at O(6).

    0 讨论(0)
  • 2020-11-28 12:36

    The code below is simpler and will work as long as the input x >= 1. input clog2(0) will get an undefined answer (which makes sense because log(0) is infinity...) You can add error checking for (x == 0) if you want:

    unsigned int clog2 (unsigned int x)
    {
        unsigned int result = 0;
        --x;
        while (x > 0) {
            ++result;
            x >>= 1;
        }
    
        return result;
    }
    

    By the way, the code for the floor of log2 is similar: (Again, assuming x >= 1)

    unsigned int flog2 (unsigned int x)
    {
        unsigned int result = 0;
        while (x > 1) {
            ++result;
            x >>= 1;
        }
    
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题