- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 ... 2^{2}= 4 2^{5}= 32 2^{10}= 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; }

- Related Questions & Answers
- Python Program to find whether a no is the power of two
- Python Program to find whether a no is power of two
- Find whether a given number is a power of 4 or not in C++
- 8085 program to find nth power of a number
- Program to check a number is power of two or not in Python
- Java program to calculate the power of a number
- C# Program to find whether the Number is Divisible by 2
- C++ Program to Calculate Power of a Number
- Find whether a given integer is a power of 3 or not in C++
- Python program to determine whether the given number is a Harshad Number
- Java Program to Check whether the input number is a Neon Number
- Program to find whether a string is alphanumeric.
- Calculate the Power of a Number in Java Program
- How to find power of a number in Python?
- Java program to find whether given number is even or odd

Advertisements