0

Using std::__builtin_ctzll() in C++ I can easily calculate log2(x). But can I calculate log3(x) and log5(x) using bitwise ?

  • well `log5(x) == log2(x)/log2(5)` so if you have `log2` then you can calculate `log3` and `log5` but you don't truly have `log2`, you just have the number of `0` bits as an integer? – Alan Birtles Aug 19 '20 at 06:51
  • Are you sure `ctz` (count *trailing* zeroes) can be used to compute `log2`? As far as I know only `clz` (count *leading* zeroes) can be used to compute `floor(log2(x)) == sizeof(x) * CHAR_BIT - 1 - clz(x)`. Note the `floor` which would heavily distort the approach `log2(x) / log2(anyBase)`. Maybe you can iteratively clear the highest bit to compute the missing fractional digits. However, such a loop would probably be slower than using the builtin `log`. – Socowi Aug 19 '20 at 07:28
  • 2
    FYI: [SO: How can you quickly compute the integer logarithm for any base?](https://stackoverflow.com/q/63411054/7478597) – Scheff's Cat Aug 19 '20 at 07:37

0 Answers0