This used to be a basic programming question asked in interviews. There is more than one solution, the trivial of which is used to verify if a person can program at all.
Idea: Take the number, divide it by two, if remainder is 0, the quotient becomes your number. Repeat this in a loop until quotient is zero.
if it is zero, the number was exactly divisible by 2, else if remainder is non zero at any given point, it is not.
The running time or complexity of this algorithm is lg n. i.e.
If n = 2^32, it will run 32 iterations, if n=8, it will run 3 iterations and so on.
The clever part is there is a better algorithm
There is a special property of numbers that are power of 2.
10 = 2
100 = 4
1000 = 8
10000 = 16
They contain exactly one on bit (1 bit). More interestingly if we subtract one from any number which is exact power of 2, the resultant will be complement of that number i.e. it will contain all those bits as on which were off in exact power of 2 and vice versa.
2-1 = 1 -> 01
4-1 = 3 -> 011
8-1 = 7 -> 0111
16-1 = 15 -> 01111
What should be the code to determine generically if a number is an exact power of 2?
If (num & num-1 == 0) // no bit is common printf(“It is an exact power of 2”);
This is constant time algorithm i.e. O(1).


Sign In
Create Account


Back to top









