C++ Program to find whether a number is the power of two?


Check if a given number is a power of 2. First check below which numbers are the power of two or not. This code checks whether the number is odd and then divide it concurrently until it becomes 0 or odd. If it becomes 0 then it is a power 2 else it is not.

A better choice is to take the log of the number. If it is an integer, then n is a power of 2 else not. Numbers that are powers of 2:

2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ...
22 = 4
25 = 32
210 = 1024


Input: 8
Output: Number is power of 2

Explanation

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

By simply repeatedly dividing N by 2 if N is an even number. If it end up at 1 then N is a power of 2

Example

#include <iostream>
using namespace std;
int main() {
   int n=8;
   if(n>0) {
      while(n%2 == 0) {
         n/=2;
      }
      if(n == 1) {
         cout<<"Number is power of 2"<<endl;
      }
   }
   if(n == 0 || n != 1) {
      cout<<"Number is not power of 2"<<endl;
   }
   return 0;
}

Updated on: 20-Aug-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements