
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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?
In this article, we will implement a C++ program to find whether a number is a power of two.
So, you are given a positive integer n; the task is to find if the given number is a power of 2 or not. Let's see some of the numbers that represent the power of two.
2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ...
Example Scenario
Let's see the following example scenario:
Input: 4 Output: yes Explanation: 22 = 4 Input: 16 Output: yes Explanation: 24 = 16 Input: 5 Output: no Explanation: 5 does not come under the power of 2.
Checking Number is Power of Two Using Logarithmic Approach
This is a simple approach here we take the log of the number on base 2 and if you get an integer then the number is a power of 2.
Example
In the following example, we implement a C++ program to check whether a number is the power of two using a logarithmic approach:
#include <bits/stdc++.h> using namespace std; // Function to check if x is power of 2 bool is_power_of_two(int n) { return (ceil(log2(n)) == floor(log2(n))); } int main() { is_power_of_two(32) ? cout << "Number is power of 2" << endl : cout << "Number is not power of 2" << endl; is_power_of_two(18) ? cout << "Number is power of 2" << endl : cout << "Number is not power of 2" << endl; return 0; }
Following is the output of the code:
Number is power of 2 Number is not power of 2
Checking Number is Power of Two Using Iterative Division Approach
It simply repeatedly divides N by 2 if it is an even number. If it ends up at 1, then N is a power of 2.
Example
In the following example, we implement a C++ program to check whether a number is the power of two using a division method or iterative division approach:
#include <iostream> using namespace std; int main() { int n=32; 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; }
Following is the output of the code:
Number is power of 2