n = 2 ^ x
I know the value of n
, what is the efficient way to find the value of x
?
n = 2 ^ x
I know the value of n
, what is the efficient way to find the value of x
?
Assuming you mean n = 2x, then this is called logarithm base 2.
In C you can write:
double n = 512;
// ...
double x = log(n) / log(2); // 9
That formula works for any base (replace 2
by the base). As pointed out by Kii, since C99 there is in fact a function specifically for base 2
:
double x = log2(n);
Note that using <tgmath.h>
instead of <math.h>
will enable autodetection of which floating point type you are using.
I guess you are thinking of integer numbers, e.g. long
or int
(and their unsigned
variants) and if you are using a recent GCC compiler, and if you are sure that n
is a power of 2, then consider using the __builtin_ffs
builtin (or __builtin_ffsll
for long long
, etc...) function (find first set bit). It is probably the fastest.
IF it is a positive int or an unsigned int, you can shift right the single 1 bit till you have only zeroes, and count how many times you shifted.
EDIT for the sake of completeness (yeah, I know it is bugged for num = 0 :-p):
#include "stdio.h"
int main(void)
{
unsigned int num = 65536;
int pow = -1;
while (num > 0)
{
num >>= 1;
++pow;
}
printf("%d ", pow);
return 0;
}
The obvious way:
unsigned int v; // 32-bit word to find the log base 2 of
unsigned int r = 0; // r will be lg(v)
while (v >>= 1) // unroll for more speed...
{
r++;
}
See Stanford Bit Twiddling Hacks page for fast (O(lg(N)) bit hacks to do it.
If you can use inline assembly and if the input is integer, the fastest method would be to count the position of the most-significant bit.
int n = 9;
__asm
{
mov eax, n
bsr eax, eax
mov n, eax
}
printf("%d", n);