Wednesday, January 1, 2014

To find whether a number is in power of 2 by counting number of 1 bits


20=1 (or 2^0=1) Read as 2 raised to power 0
21=2 (or 2^1=2) Read as 2 raised to power 1
22=4 (2*2=4)
23=8 (2*2*2=8)
24=16
25=32
As previously explained, 32 is 2 raise to power 5 and 22 does not come in power of 2.

So is there anything special in these number. 
Yes, there binary representation is intuitively special.

1     = 0000 0001
2     = 0000 0010
4     = 0000 0100
8     = 0000 1000
16   = 0001 0000
32   = 0010 0000
64   = 0100 0000
128 = 1000 0000

Any number which exist in power of 2 has only single 1 in its representation.

So, we can convert a number to binary and if it has only a single 1, it is in power of 2.And write a program that does not use pow() function of math.h header file

 The conversion to binary form is already explained in earlier blog

#include<stdio.h>
int main()
{
    int num, num_copy, rem, count,power;
        printf("\nEnter number:");
        scanf("%d",&num);

    num_copy=num;
    count=0;
        power=-1;

        while(num>0)
        {
        rem=num%2;

        if(rem==1)
            count++;

        num=num/2;
        power++;
    }

        if(count==1)
        printf("%d is 2 raised to %d" ,num_copy,power);
    else
        printf("number not in power of 2");


    return 0;

}
      
        
        








No comments:

Post a Comment