C++ program to check for the power of two

In this program, you will learn about C++ program to check for the power of two with and without using function.

There are various ways to check if a given number is a power of 2. First check below which numbers are the power of two or not.

Numbers that are power of 2:
2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ...
22 = 4
25 = 32
210 = 1024

We will solve this problem in two different ways:

  • Using bitwise operator
  • Using function

C++ program to check whether a number is a power of 2 or not.

a//C++ program to check whether a number is power of 2 or not

#include <iostream>
using namespace std;

int main()
{
   int num;

   cout << "Enter the number you want to test: ";
   cin >> num;

   //condition to check whether number is power of two or not
   //performing bitwise operation
   if((num != 0) && ((num &(num - 1)) == 0))
      cout << num << " is a power of 2." << endl;

   else
      cout << num << " is not a power of 2." << endl;

   return 0;
} //end main

Output

C++ program to check for the power of two output

Explanation

In the above program, we have used bitwise operators.

Logic to check if a number is the power of 2.

If the number is a power of 2 then the bits of the previous number is compliment to the bits that number.

Therefore, if condition compares the bits of number with the previous number.

C++ program to check for the power of two using function

//C++ program to check for the power of using function
#include <iostream>
using namespace std;

//function prototype for checking power of two
int checkPowerofTwo(int n);

int main()
{
   int num;

   cout << "Enter the number you want to test: ";
   cin >> num;

   if (checkPowerofTwo(num) == 1)
      cout << num << " is a power of 2." << endl;
   else
      cout << num << " is not a power of 2." << endl;

   return 0;
}

//function body
int checkPowerofTwo(int x)
{
   //checks whether a number is zero or not
   if (x == 0)
   return 0;

   //true till x is not equal to 1
   while( x != 1)
   {
      //checks whether a number is divisible by 2
      if(x % 2 != 0)
         return 0;
      x /= 2;
   }
   return 1;
}

Output

Enter the number you want to test: 20
20 is not a power of 2.

Enter the number you want to test: 1024
1024 is a power of 2.