Write one line C function to find whether a no is power of two

1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.

2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

#include<stdio.h>
#define bool int

/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
  if (n == 0)
    return 0;
  while (n != 1)
  {
    if (n%2 != 0)
      return 0;
    n = n/2;
  }
  return 1;
}

/*Driver program to test above function*/
int main()
{
  isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(17)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(16)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(2)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(18)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(1)? printf("Yes\n"): printf("No\n");
  return 0;
}

Output:

No
No
Yes
Yes
No
Yes

3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see http://geeksforgeeks.org/?p=1176 for counting set bits.

4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.

For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111

So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to Mohammad for adding this case).
Below is the implementation of this method.

#include<stdio.h>
#define bool int

/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
  /* First x in the below expression is for the case when x is 0 */
  return x && (!(x&(x-1)));
}

/*Driver program to test above function*/
int main()
{
  isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(17)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(16)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(2)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(18)? printf("Yes\n"): printf("No\n");
  isPowerOfTwo(1)? printf("Yes\n"): printf("No\n");
  return 0;
}

Output:

No
No
Yes
Yes
No
Yes

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above





  • Aveek Biswas

    Is writing an one line Java function for this possible?

  • Guest

    int isPowerOfTwo(int n)

    {

    while(!(n&1))

    n>>=1;

    if(n==1)return 1;

    else return 0;

    }

  • Amit Kumar

    void main()

    {
    int value=8,i=1,count=0;
    while (i){

    if(value & i){ ++count;
    }
    i=i<<1;
    }
    printf(" value: %d", count);

    if(count == 1) {
    printf("Number is power of two");
    }

    }

  • Raman Classes

    ((n&(n-1))==0) ? printf(“Power of 2″) :printf(“Not power of 2″);

  • gargsanjay

    in method 5
    at one place u wrote n&(!(n)&n-1)
    and at one place n&&(!(n)&(n-1)

     
    /* Paste your code here (You may delete these lines if not writing code) */
     
  • Hanish Bansal

    There is an error in Method 2.
    For numbers of the form 2^x + 1 (e.g. 17), it returns 1.

    Correct function :
    bool isPowerOfTwo(int n)
    {
    if(n == 0)
    return 0;
    while(n != 1)
    {
    if(n%2 != 0)
    return 0;
    n = n/2;
    }
    return 1;
    }

    • amit

      yesss…method 2 is wrong

       
      /* Paste your code here (You may delete these lines if not writing code) */
       
      • GeeksforGeeks

        @Hanish Bansal: Thanks for pointing out the issue and solution. We have updated the post. Keep it up!

        @amit: Thanks for bringing it to notice.

  • Rohit

    we can find this by checking 2’s compliment of that number as 2’s compliment of a number(which is power of 2) is the number itself.
    therefore
    if((~x+1)==x)
    then power of 2
    else
    not
    simple 1 line solution

    • dgDinkar

      2’s compliment of any number gives it’s negative number…
      then how it can be equal??

  • http://www.fireupyourbusiness.co.za/programme/ de-captcher

    I love your blog.. very nice colors & theme. Did you design this
    website yourself or did you hire someone to do
    it for you? Plz reply as I’m looking to design my own blog and would like to find out where u got this from. thanks a lot

  • krazykoder

    check if a log2 of the number is an integer or not!!

     
    /* Paste your code here (You may delete these lines if not writing code) */
    #include <stdio.h>
    #include <math.h>
    
    int main(){
        int n=9;
        float log=log2(n);
        int check=((int )(log*100))%100;// checking till precision of 2 decimal pace digits
        if(!check)
        printf("yeaa");
        else
        printf("noo");
    
    }
    
     
  • krazykoder

    check if a log2 of the number is an integer or not!!

     
    /* Paste your code here (You may delete these lines if not writing code) */
    #include <stdio.h>
    #include <math.h>
    
    int main(){
        int n=9;
        float log=log2(n);
        int check=((int )(log*100))%100;// checking till precision of 2 decimal pace digits
        if(!check)
        printf("yeaa");
        else
        printf("nooooo");
    
    }
    
     
  • krazykoder
     
    /* Paste your code here (You may delete these lines if not writing code) */
    #include <stdio.h>
    #include <math.h>
    
    int main(){
        int n=9;
        float log=log2(n);
        int check=((int )(log*100))%100;// checking till precision of 2 decimal pace digits
        if(!check)
        printf("yeaa");
        else
        printf("nooooo");
    
    }
    
     
  • ritesh_nitw

    One line and a single BITWISE AND is sufficient

     
    x&(x-1)==0?print x is power of two : print Nops!!
     
  • anji.swe

    sorry,….
    conditions
    n&(1-n)==n

    n&(2+~n)==n

    are giving false for one, and true for zero.

  • anji.swe

    if n is a power of two then ..

    (n&(-n)) = n
    (n&(1+~n)) = n
    (n & (~(n & (n – 1)))) =n
    (n & (n – 1))=0
    ~(n & (n – 1))=-1
    !(n & (n – 1)) =1

    so…
    use any one of them in if condition and evaluate n…

    :)

    0,1 are treated as powers of 2, if dont want put a condition

  • anji.swe

    if n is a power of two then ..

    (n&(1-n)) = n
    (n&(1+~n)) = n
    (n & (~(n & (n – 1)))) =n
    (n&(2+~n)) =n
    (n & (n – 1))=0
    ~(n & (n – 1))=-1
    !(n & (n – 1)) =1

    so…
    use any one of them in if condition and evaluate n…

    :)

  • anji.swe

    if n is a power of two then ..

    (n&(1-n)) = n
    (n&(1+~n)) = n
    (n & (~(n & (n – 1)))) =n
    (n&(2+~n)) =n
    (n & (n – 1))=0
    ~(n & (n – 1))=-1
    !(n & (n – 1)) =1

    so…
    use any one of then in if condition and evaluate n…

    :)

  • ap

    if (x & (~x + 1) == x ) then it is a power of two

    • ap

      correct me if i am missing any

  • pnh

    void twoPowerN(int n)
    {
    printf(“%d is %s power of 2 \n “,n, (((n)&(n-1))==0?”a”:”not a”));
    }

  • mm10

    Correction from my previous comment

     
    if((n&1)==1) // not a power of 2
    if((n&1)==0) // power of 2
     

    Would this code not be feasible?

    Thanks
    MM

    • Sandeep

      @mm10:
      This code would check for multiple of 2, not power of 2. For example, see this pogram. It prints “n is a power of 2″.

    • amit nanda

      1 is also a power of 2 but your code give wrong result.

    • maruti kutre

      If I am correct above solution is wrong power of 2 means 2^n n ranging from 1……any number. its not any number/2 ==0. 6 is divisible by 2 but its not power of 2. correct me if I am wrong.

  • geeksforgeeks

    @manoj: We have added few more words in solution 2 to elaborate the point. Hope it makes sense now.

  • manoj

    Solution (2) doesn’t seem correct. 2’s powers are 2,4,8,16,… and solution (2) would report 6,10,12,14,… also powers of 2.

    • pnh

      6 = 110 and 5 = 101
      (n)&(n-1) = (110 & 101) is not equal to zero….
      so solution (2),
      void twoPowerN(int n)
      {
      printf(“%d is %s power of 2 \n “,n, (((n)&(n-1))==0?”a”:”not a”));
      }

      works for all value of n !!!

  • geeksforgeeks

    @Mohammad: Thanks very much for suggesting this case. We have added it to the original post.

  • Mohammad

    Nice solution but you should pay special attention to the case when x = 0. The updated solution should be

    return x && (!(x&(x-1)));

    I just added the term “x && ”

    Thanks

    • Aveek Biswas

      Could you suggest an equivalent one line function in JAVA?

    • neha

      pls explain mohammad, how u solve it by ussing “&&” ?