 Home >>Cpp Programs >Program to find whether a no is power of two in CPP

# Program to find whether a no is power of two in CPP

### C++ program to check if number is power of 2 using Bitwise operator

In this example, we will see a C++ program through which we can check if the given number is power of 2 or not.

In this program, we will divide the given number by 2 until the number will not get 0 or 1. This algorithm takes the O(log(n)) complexity to solve this problem.

Program:
``````
#include <iostream>
using namespace std;
int main()
{
// declaring the array n
int n[]={4,9,15,16,20,22,25,32,45,64,72,80,100,128,256};
int i;

for(i=0;i<15;i++)
{
cout<< n[i] << " is power of 2 : ";
// use of bitwise AND (&) operator
if((n[i]& (n[i]-1))==0)
cout<<"True"<<endl;
else
cout<<"False"<<endl;
}
return 0;
}
```
```
Output:
4 is power of 2 : True
9 is power of 2 : False
15 is power of 2 : False
16 is power of 2 : True
20 is power of 2 : False
22 is power of 2 : False
25 is power of 2 : False
32 is power of 2 : True
45 is power of 2 : False
64 is power of 2 : True
72 is power of 2 : False
80 is power of 2 : False
100 is power of 2 : False
128 is power of 2 : True
256 is power of 2 : True