I am trying to calculate the time complexity for a function return below-
int isPowerof2(unsigned int num)
{
if(((~num)&1) == 1)
return 1;
return 0;
}
I think it should be O(1) but i am not sure the complexity for negation. Can somebody please help me in understanding how to identify the complexity for this. Thanks!
Edit- What if in case of a single number consider it as an n inputs and the functions checks for power of 2 , what would be the complexity in that case
A power of two, represented in binary, has exactly one bit set, all others are zero.
Subtracting one will invert all bits right of of and including the rightmost one:
If
numis in fact a power of two, there is a single bit set in total, subtracting one will render that bit zero and set all bits to its right to one.It follows, that
numandnum - 1cannot share any set bits. Thus,num & (num - 1)evaluates to 0.If
numis not a power of two (and not zero), there are at least two bits set. When subtracting one, only the rightmost set bit is changed and those to its right, it follows, that the other ones will not be affected.Thus,
numandnum - 1share at most one set bit. We conclude thatnum & (num - 1)cannot evaluate to zero fornumnot zero and not a power of two.It follows that the correct check is:
num && !(num & (num - 1))Complexity: On a regular computer, all binary operations happen in constant time. Because there is a fixed amount of constant time operations, the entire function will return in constant time:
O(1).When you perform
ncalls to that function, you do a constant time amount of work each time you call it. Whenndoubles, the amount of work doubles. It follows, that the complexity for that case isO(n).