- 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
- 8085 program to find nth power of a number
- C# Program to find whether the Number is Divisible by 2
- C++ Program to Calculate Power of a Number
- C program to calculate power of a given number
- Java program to calculate the power of a number
- Find power of a number using recursion in C#
- C++ program to find whether there is a path between two cells in matrix
- How to find power of a number in Python?
- Power of Two in C
- Check if a number is a power of another number in C++
- Python program to determine whether the given number is a Harshad Number
- Program to find whether a string is alphanumeric.
- Bash program to find A to the power B?

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

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

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

#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; }

Advertisements