How to check if a number is a power of 2 in C++
Overview
In this shot, we'll see how to check if a number is a power of 2 using different approaches in C++.
Approach 1
To check if a given number is a power of 2, we can continuously divide the number by 2, on the condition that the given number is even.
After the last possible division, if the value of the number is equal to 1, it is a power of 2. Otherwise, it is not.
Example
#include <iostream>using namespace std;int main() {int n, i;// reading value of n from usercin >> n;i = n;if (i > 0) {// continously divide i if it is evenwhile (i % 2 == 0) {i = i / 2;}// check if n is a power of 2if (i == 1) {cout << n << " is a power of 2";} else {cout << n << " is not a power of 2";}} else {cout << "Enter a valid positive number";}return 0;}
Enter the input below
Explanation
- Line 5: We declare two variables
nandi. - Line 7–8: We read the value of
ngiven by the user and also store it ini. - Line 12–14: We continuously divide the value of
iif it is an even number. - Line 17–22: We check if the number
nis a power of 2 by checking its value.
Approach 2
To check if a given number is a power of 2, we can use the bit manipulation technique.
If the & operation between the given number n and given number minus one n-1 gives us 0, it is a power of 2. Otherwise, it is not.
Example
#include <iostream>using namespace std;int main() {int n;// reading value of n from usercin >> n;if (n > 0) {// & operation between n and n - 1int i = n & (n - 1);// check if n is a power of 2if (i == 0) {cout << n << " is a power of 2";} else {cout << n << " is not a power of 2";}} else {cout << "Enter a valid positive number";}return 0;}
Enter the input below
Explanation
- Line 5: We declare a variable
n. - Line 7: We read the value of
ngiven by the user. - Line 11: We perform the
&operation betweennandn-1. - Line 14–18: We check if the number
nis a power of 2 by checking its value.
Approach 3
To check if a given number is a power of 2, we can calculate the log2() of the given number and pass it to the ceil() and floor() methods.
If the ceil() and floor() of the passed value are equal, it is a power of 2. Otherwise, it is not.
Example
#include <iostream>#include <cmath>using namespace std;int main() {int n;// reading value of n from usercin >> n;if (n > 0) {// calculate log2() of nfloat i = log2(n);// check if n is a power of 2if (ceil(i) == floor(i)) {cout << n << " is a power of 2";} else {cout << n << " is not a power of 2";}} else {cout << "Enter a valid positive number";}return 0;}
Enter the input below
Example
- Line 6: We declare a variable
n. - Line 8: We read the value of
ngiven by the user. - Line 12: We calculate the
log2()value ofnandiis afloat. - Line 14–18: We check if the number
nis a power of 2 by checking its value.