Search code examples
c++mathlogarithm

Calculate the log base n with Shift left or Shift right


I have a little problem. Who knows how we can calculate the log base n with Shift_L or Shift_R?

for example: for n=2 we had this solution:

int log(int n){
int res = 0;
while((n>>=1))
    res++;
return res;
}

Solution

  • You don't seem to want the logarithm for a base b, but the largest integer n so that n <= log_b(x). If that's the case, the following function should serve your needs:

    int intlog(double base, double x) {
        return (int)(log(x) / log(base));
    }