Given a positive integer, write a function to find if it is a power of two or not.
Examples :
Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 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
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 2bool isPowerOfTwo(int n){ if(n==0) return false; return (ceil(log2(n)) == floor(log2(n)));}// Driver programint 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 |
C
// C Program to find whether a// no is power of two#include<stdio.h>#include<stdbool.h>#include<math.h>/* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ if(n==0) return false; return (ceil(log2(n)) == floor(log2(n)));}// Driver programint main(){ isPowerOfTwo(31)? printf("Yes\n"): printf("No\n"); isPowerOfTwo(64)? printf("Yes\n"): printf("No\n"); return 0;}// This code is contributed by bibhudhendra |
Java
// Java Program to find whether a// no is power of twoclass GFG{/* Function to check if x is power of 2*/static boolean isPowerOfTwo(int n){ if(n==0) return false;return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2)))));}// Driver Codepublic static void main(String[] args){ if(isPowerOfTwo(31)) System.out.println("Yes"); else System.out.println("No"); if(isPowerOfTwo(64)) System.out.println("Yes"); else System.out.println("No");}}// This code is contributed by mits |
Python3
# Python3 Program to find # whether a no is # power of twoimport math# Function to check# Log base 2def Log2(x): if x == 0: return false; return (math.log10(x) / math.log10(2));# Function to check# if x is power of 2def isPowerOfTwo(n): return (math.ceil(Log2(n)) == math.floor(Log2(n)));# Driver Codeif(isPowerOfTwo(31)): print("Yes");else: print("No");if(isPowerOfTwo(64)): print("Yes");else: print("No"); # This code is contributed # by mits |
C#
// C# Program to find whether // a no is power of twousing System;class GFG{ /* Function to check if x is power of 2*/static bool isPowerOfTwo(int n){ if(n==0) return false; return (int)(Math.Ceiling((Math.Log(n) / Math.Log(2)))) == (int)(Math.Floor(((Math.Log(n) / Math.Log(2)))));}// Driver Codepublic static void Main(){ if(isPowerOfTwo(31)) Console.WriteLine("Yes"); else Console.WriteLine("No"); if(isPowerOfTwo(64)) Console.WriteLine("Yes"); else Console.WriteLine("No");}}// This code is contributed // by Akanksha Rai(Abby_akku) |
PHP
<?php// PHP Program to find // whether a no is // power of two// Function to check// Log base 2function Log2($x){ return (log10($x) / log10(2));}// Function to check// if x is power of 2function isPowerOfTwo($n){ return (ceil(Log2($n)) == floor(Log2($n)));}// Driver Codeif(isPowerOfTwo(31))echo "Yes\n";elseecho "No\n";if(isPowerOfTwo(64))echo "Yes\n";elseecho "No\n"; // This code is contributed // by Sam007?> |
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.
C++
#include <bits/stdc++.h>using namespace std;/* Function to check if x is power of 2*/bool isPowerOfTwo(int n) { if (n == 0) return 0; while (n != 1) { if (n%2 != 0) return 0; n = n/2; } return 1; } /*Driver code*/int main() { isPowerOfTwo(31)? cout<<"Yes\n": cout<<"No\n"; isPowerOfTwo(64)? cout<<"Yes\n": cout<<"No\n"; return 0; } // This code is contributed by rathbhupendra |
C
#include<stdio.h>#include<stdbool.h>/* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ if (n == 0) return 0; while (n != 1) { if (n%2 != 0) return 0; n = n/2; } return 1;}/*Driver program to test above function*/int main(){ isPowerOfTwo(31)? printf("Yes\n"): printf("No\n"); isPowerOfTwo(64)? printf("Yes\n"): printf("No\n"); return 0;} |
Java
// Java program to find whether// a no is power of twoimport java.io.*;class GFG { // Function to check if // x is power of 2 static boolean isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } // Driver program public static void main(String args[]) { if (isPowerOfTwo(31)) System.out.println("Yes"); else System.out.println("No"); if (isPowerOfTwo(64)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Nikita tiwari. |
Python3
# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo(n): if (n == 0): return False while (n != 1): if (n % 2 != 0): return False n = n // 2 return True# Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No')if(isPowerOfTwo(64)): print('Yes')else: print('No')# This code is contributed by Danish Raza |
C#
// C# program to find whether// a no is power of twousing System;class GFG{ // Function to check if // x is power of 2 static bool isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } // Driver program public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No"); Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No"); }}// This code is contributed by Sam007 |
PHP
<?php// Function to check if// x is power of 2function isPowerOfTwo($n){if ($n == 0) return 0;while ($n != 1){ if ($n % 2 != 0) return 0; $n = $n / 2;}return 1;}// Driver Codeif(isPowerOfTwo(31)) echo "Yes\n";else echo "No\n";if(isPowerOfTwo(64)) echo "Yes\n";else echo "No\n";// This code is contributed // by Sam007?> |
Output :
No Yes
3. Another way is to use this simple recursive solution. It uses the same logic as the above iterative solution but uses recursion instead of iteration.
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std;// Function which checks whether a // number is a power of 2bool powerOf2(int n){ // base cases // '1' is the only odd number // which is a power of 2(2^0) if (n == 1) return true; // all other odd numbers are not powers of 2 else if (n % 2 != 0 || n ==0) return false; // recursive function call return powerOf2(n / 2); }// Driver Codeint main(){ int n = 64;//True int m = 12;//False if (powerOf2(n) == 1) cout << "True" << endl; else cout << "False" << endl; if (powerOf2(m) == 1) cout << "True" << endl; else cout << "False" << endl;}//code contributed by Moukthik a.k.a rowdyninja |
Python3
# Python program for above approach# function which checks whether a # number is a power of 2 def powerof2(n): # base cases # '1' is the only odd number # which is a power of 2(2^0) if n == 1: return True # all other odd numbers are not powers of 2 elif n%2 != 0 or n == 0: return False #recursive function call return powerof2(n/2) # Driver Codeif __name__ == "__main__": print(powerof2(64)) #True print(powerof2(12)) #False #code contributed by Moukthik a.k.a rowdyninja |
C#
// C# program for above approachusing System;class GFG{ // Function which checks whether a // number is a power of 2static bool powerOf2(int n){ // Base cases // '1' is the only odd number // which is a power of 2(2^0) if (n == 1) return true; // All other odd numbers // are not powers of 2 else if (n % 2 != 0 || n == 0) return false; // Recursive function call return powerOf2(n / 2); }// Driver code static void Main() { int n = 64;//True int m = 12;//False if (powerOf2(n)) { Console.Write("True" + "\n"); } else { Console.Write("False" + "\n"); } if (powerOf2(m)) { Console.Write("True"); } else { Console.Write("False"); }}}// This code is contributed by rutvik_56 |
True False
4. All power of two numbers has only one-bit set. So count the no. of set bits and if you get 1 then the number is a power of 2. Please see Count set bits in an integer for counting set bits.
5. 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 becomes 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).
Below is the implementation of this method.
C++
#include <bits/stdc++.h>using namespace std;#define bool int /* Function to check if x is power of 2*/bool isPowerOfTwo (int x) { /* First x in the below expression is for the case when x is 0 */ return x && (!(x&(x-1))); } /*Driver code*/int main() { isPowerOfTwo(31)? cout<<"Yes\n": cout<<"No\n"; isPowerOfTwo(64)? cout<<"Yes\n": cout<<"No\n"; return 0; } // This code is contributed by rathbhupendra |
C
#include<stdio.h>#define bool int/* Function to check if x is power of 2*/bool isPowerOfTwo (int x){ /* First x in the below expression is for the case when x is 0 */ return x && (!(x&(x-1)));}/*Driver program to test above function*/int main(){ isPowerOfTwo(31)? printf("Yes\n"): printf("No\n"); isPowerOfTwo(64)? printf("Yes\n"): printf("No\n"); return 0;} |
Java
// Java program to efficiently // check for power for 2class Test{ /* Method to check if x is power of 2*/ static boolean isPowerOfTwo (int x) { /* First x in the below expression is for the case when x is 0 */ return x!=0 && ((x&(x-1)) == 0); } // Driver method public static void main(String[] args) { System.out.println(isPowerOfTwo(31) ? "Yes" : "No"); System.out.println(isPowerOfTwo(64) ? "Yes" : "No"); }}// This program is contributed by Gaurav Miglani |
Python
# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo (x): # First x in the below expression # is for the case when x is 0 return (x and (not(x & (x - 1))) )# Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No') if(isPowerOfTwo(64)): print('Yes')else: print('No') # This code is contributed by Danish Raza |
C#
// C# program to efficiently // check for power for 2using System;class GFG{ // Method to check if x is power of 2 static bool isPowerOfTwo (int x) { // First x in the below expression // is for the case when x is 0 return x != 0 && ((x & (x - 1)) == 0); } // Driver method public static void Main() { Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No"); Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No"); }}// This code is contributed by Sam007 |
PHP
<?php// PHP program to efficiently // check for power for 2// Function to check if// x is power of 2function isPowerOfTwo ($x){// First x in the below expression// is for the case when x is 0 return $x && (!($x & ($x - 1)));}// Driver Codeif(isPowerOfTwo(31)) echo "Yes\n" ;else echo "No\n";if(isPowerOfTwo(64)) echo "Yes\n" ;else echo "No\n"; // This code is contributed by Sam007?> |
Output :
No Yes
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find power of power under mod of a prime
- Find the sum of power of bit count raised to the power B
- Find whether a given number is a power of 4 or not
- Find whether a given integer is a power of 3 or not
- Check if given number is a power of d where d is a power of 2
- Compute power of power k times % m
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Check whether a given Number is Power-Isolated or not
- Given two numbers as strings, find if one is a power of other
- Find two numbers whose difference of fourth power is equal to N
- Find whether only two parallel lines contain all coordinates points or not
- Given a HUGE number check if it's a power of two.
- Check if bitwise AND of any subset is power of two
- Highest power of two that divides a given number
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two
- Largest subset where absolute difference of any two element is a power of 2
- Check if ceil of number divided by power of two exist in sorted array
- Java Program to Calculate Power of a Number
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers
- Find multiple of x closest to or a ^ b (a raised to power b)

