C Programming Reference

C Programming Reference >> C Programming Short Notes >>

28/05/07 - 669 Views - Ratings :   4 of 5 / 12 Votes


Quick method to determine wether number is power of 2 using C

Level - Intermediate
      

Well if we have to determine wether a number is a power of 2 there can be tons of algorithm designed to do so using loops and conditional statements. But often there is constraint on program coded to perform under a certain complexity or efficiency.

You really dont want to waste your precious CPU processing for trivial task using giant loop or a switch statement or anything like it. Here i give you a better option, one unmatched in efficiency by any other algorithm which can do this task.

We use a mathematical concept that if we have to find wether X is a power of 2 then X ^ X-1 ( '^' Stands for XOR logic operation ) will return 0 value only when the X is a power of 2.

Now to demonstrate it using coding we will be creating a subroutine in the code below which take them number to be evaluated as input and will return 0 if number is a power of 2 and 0 otherwise.

Also we need to take case of special case in which number to evaluated is 0, which will also produce 0 as return value eventhough 0 is not a multiple of 2.

Source code below is written in C and is implementation of concept, how to determine the number is a power of 2.

#include <stdio.h>
           
int ispowerof2 (int x) // Our Function
{
   if (!x || (x&(x-1)))
      return 1;
   else
      return 0; 
}
 
int main ()
{
  int number;
                 
  printf ("\nEnter A Number : ");
  scanf ("%d", &number);
               
  if (ispowerof2 (number))
    {
      printf ("\n\nNot a power of 2");
    }
  else
    {
      printf ("\n\nPower of 2");
    }
               
  return 0;

} 
 

 

Reader Comments -

Author Comments
Add Comments 


Name :    
Reply :   


Rating :

Code :
Code

 

 
© 2006 cencyclopedia.com