I tried using log but it is consuming more time than the iterative version for finding the answer. The number is integer.
Using log:-
int ans = (log(x)/log(2));
Iterative version:-
int temp;
while(x)
{
temp = temp/2;
count++;
}
count--;
I tried using log but it is consuming more time than the iterative version for finding the answer. The number is integer.
Using log:-
int ans = (log(x)/log(2));
Iterative version:-
int temp;
while(x)
{
temp = temp/2;
count++;
}
count--;
Basic Integer datatype
for integers on x86 architecture there is a single O(1)
instruction for this:
that returns position of MSB set bit. So you do not need to do the iterative O(log(n))
dividing, shifting or bin-search. To make sure the sign (2'os complement) does not mess this up for negative numbers use abs
value for this.
bigints
For these you need to check the MSW non zero WORD. and use #1 on it. This is O(log(n))
. Where n
is the number you are testing.
floating point
These are usually very simple O(1)
as you just extract exponent which tells you the position of MSB set bit directly.
Also log2
is directly implemented by FPU HW for basic floating datatypes on most architectures but they will not return integer style result ...