Tuesday, April 13, 2010

Efficient method to find if a number is power of 2

Finding if a number is power of 2 is pretty straight forward when you think in terms of bits. One way is to count the number of ones in binary representation. If number of ones is one then the number is power of 2. To illustrate this consider powers of 2 like 1,2,4,8,16 and so on. how are they represented in binary? 1, 10, 100, 1000, 10000 and so on. What do they have in common? All of them contain only single bit that has value 1 and rest are 0. This method is effective but still it requires O(n) time in the worst case (where n is the maximum number of bits in the number).

Lets think of it in a different way. What sort of numbers are power of 2? If we look at the bit pattern we can say that the numbers which have a single 1 bit and the left and right bits from the 1 bit are all zeros. So what will be the number that represents the right bits? If you deduct 1 from given number N (i.e. N-1), then it should give number with all right bits set if the number is power of 2. What this means is that if we AND the given number N with N-1 and the result is 0 then the number is power of 2 otherwise not. If a number is not power of 2, it will have atleast single 1 on the right of it and the AND operation would result a number greater then 0. The check for power of 2 can be written in terms of code as:




bool is_power(unsigned int n) {

return n !=0 && (n & n-1) == 0;
}

No comments:

Post a Comment