Home >>Cpp Programs >Program to find whether a no is power of two in CPP
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;
}