# C++ Program to find whether a no is power of two

Given a positive integer, write a function to find if it is a power of two or not.

**Examples :**

Input : n = 4 Output : Yes 2^{2}= 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 2^{5}= 32

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

## C++

`// C++ Program to find whether a ` `// no is power of two ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to check if x is power of 2 ` `bool` `isPowerOfTwo(` `int` `n) ` `{ ` ` ` `return` `(` `ceil` `(log2(n)) == ` `floor` `(log2(n))); ` `} ` ` ` `// Driver program ` `int` `main() ` `{ ` ` ` `isPowerOfTwo(31) ? cout << ` `"Yes"` `<< endl : cout << ` `"No"` `<< endl; ` ` ` `isPowerOfTwo(64) ? cout << ` `"Yes"` `<< endl : cout << ` `"No"` `<< endl; ` ` ` ` ` `return` `0; ` `} ` ` ` `// This code is contributed by Surendra_Gangwar ` |

*chevron_right*

*filter_none*

**Output:**

No Yes

**2. **Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

**3. **All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.

**4. ** If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.

For example for 4 ( 100) and 16(10000), we get following after subtracting 1

3 –> 011

15 –> 01111

So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case).

Please refer complete article on Program to find whether a no is power of two for more details!

## Recommended Posts:

- Create Directory or Folder with C/C++ Program
- C Program to Swap two Numbers
- C++ Program to concatenate two strings using Operator Overloading
- C++ Program to implement Symbol Table
- C++ Program for Bubble Sort
- C++ Program for Heap Sort
- C/C++ Program for n-th Fibonacci number
- C++ Program for ShellSort
- C++ Program for Longest Common Subsequence
- C/C++ Program for Longest Increasing Subsequence
- C++ Program for Longest Increasing Subsequence
- C++ Program for GCD of more than two (or array) numbers
- C++ Program for Common Divisors of Two Numbers
- C++ Program for Bitonic Sort
- C++ Program for Bitonic Sort