If I know the number number y and know that 2^x=y, how do I compute x?
+11
A:
Base 2 logarithm function:
log2(y)
which is equivalent to:
log(y) / log(2)
for arbitrary base.
Mehrdad Afshari
2009-05-15 11:15:58
That log trick is so handy... I was always wondering how to do arbitrary base logs on calculators.
Zifre
2009-05-15 11:32:52
Thanks! I was actually on to that answer but my check on the calculator told me otherwise. I then realised the calculator uses log10.
Johan Öbrink
2009-05-15 11:42:07
BTW, I have a question : don't you have to ensure that parameters you provide to log2 are strictly positive ?
yves Baumes
2009-05-15 12:03:48
@yves: It's a math question and it's not concerned about implementation details. log is not defined for negative numbers (not considering complex numbers, of course), so yes, you might want to validate the input in real world applications.
Mehrdad Afshari
2009-05-15 12:09:27
If we add negative numbers into the picture: http://www.technick.net/public/code/cp_dpage.php?aiocp_dp=guide_dft_logarithms_negative_imagina
Mehrdad Afshari
2009-05-15 12:11:37
+2
A:
If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.
Example code:
int power(int num)
{
if(0 == num)
{
return 0;
}
int count = 0;
do
{
++count;
num = num >> 1;
}while(! (num & 1) && num > 0);
return count;
}
Naveen
2009-05-15 11:21:35
Yeah, provided that x is guaranteed to be an integer of course. This *would* be the most efficient method in that case.
Noldorin
2009-05-15 11:23:05
Most processors have built in way for doing this in a single instruction (`bsr` in x86, for instance)
Mehrdad Afshari
2009-05-15 11:26:16
+2
A:
And in case you don't have a log
function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)
Artelius
2009-05-15 11:22:17
Brute force approach, always good :) Probably quicker for small values of y than trying to take a log as well (optimisation anyone? 'if y < 1000000 do_division() else take_log()' :))
workmad3
2009-05-15 11:37:19
Funny, that. If you have a coprocessor, the threshold where the log is faster will be fairly low.
Artelius
2009-05-16 11:11:43
A:
If x is a positive integer, then, following code will be more efficient..
unsigned int y; // You know the number y for which you require x..
unsigned int x = 0;
while (y >>= 1)
{
x++;
}
x is the answer!
lakshmanaraj
2009-05-18 14:03:16