In this shot, we'll see how to check if a number is a power of 2 using different approaches in C++.
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.
#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
n
and i
.n
given by the user and also store it in i
.i
if it is an even number.n
is a power of 2 by checking its value.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.
#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
n
.n
given by the user.&
operation between n
and n-1
.n
is a power of 2 by checking its value.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.
#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
n
.n
given by the user.log2()
value of n
and i
is a float
.n
is a power of 2 by checking its value.