Check given number is power of 4

This program is to check whether a given number is power of 4

Condition for a number to be power of 4:

  • If the number of bit set is 1
  • The number of unset bit before the first set is even

Example:

number: 16 = 0001 0000
Here number of bit set is 1 and clear bit before set bit is 4(even)

Implementation:

#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)

int display_binary(unsigned int num)
{
   int i;
   for(i = MAX_BIT-1; i>=0; i--)
   {
       if((num >> i)&1)
         printf("1");
       else
         printf("0");
   }
}

int is_power_4(int num)
{
    int i =0;
    int set=0;
    int unset =0;
    for (i; i < MAX_BIT; i++)
    {
        if ((num >>i) &1)
          set++;
        else
        {
          if(!set)
           unset++;
        }
    }
    if(set ==1 && unset %2 ==0)
      return 1;
      else
      return 0;
}

int main()
{
  unsigned int num, pos;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  int res = is_power_4(num);
  if(res)
    printf("\n The number: %d is power of 4\n", num);
  else
    printf("\n The number: %d is not power of 4\n", num);
  printf("\n Binary of a number is: ");
  display_binary(num);
 
  return 0;
}

Output:

Enter the number: 16

The number: 16 is power of 4

Binary of a number is: 00000000000000000000000000010000

Second Approach:

This approach is more efficient. The number is power of 4, if:

  • if it is a power of 2 that is (n & n-1) =0 and
  • The only bit set is at the odd position so that number of number of bit clear before the first set bit is always even.
#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)

int display_binary(unsigned int num)
{
   int i;
   for(i = MAX_BIT-1; i>=0; i--)
   {
       if((num >> i)&1)
         printf("1");
       else
         printf("0");
   }
}


int main()
{
  unsigned int num, pos;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  
  if (num !=0 && ((num & (num-1)) ==0) && (num & 0xAAAAAAAA)==0)
  printf("\n The number: %d is power of 4\n", num);
  else
    printf("\n The number: %d is not power of 4\n", num);
    
  printf("\n Binary of a number is: ");
  display_binary(num);
  
  return 0;
}

Output:

Enter the number: 17

The number: 17 is not power of 4

Binary of a number is: 00000000000000000000000000010001

Example: 16

0000 0000 0000 0000 0000 0000 0001 0000 =0X10
&
0101 0101 0101 0101 0110 0101 0101 0101 = 0XAAAAAAAA
—————————————————————–
0000 0000 0000 0000 0000 0000 0000 0000



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: