In this example, you will learn about C program to test if a number is a power of 2 in two ways.
There are various ways to check if a given number is a power of 2. First check below which numbersĀ are the power of two or not.
Numbers that are power of 2: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ... 22 = 4 25 = 32 210 = 1024
We will solve this problem in two different ways:
Let’s do it.
#include <stdio.h>
//function prototype for checking power of two
int checkPowerofTwo(int n);
int main()
{
int num;
printf("Enter the number you want to test: ");
scanf("%d", &num);
if (checkPowerofTwo(num) == 1)
printf("\n%d is a power of 2\n", num);
else
printf("\n%d is not a power of 2\n", num);
return 0;
}
//function body
int checkPowerofTwo(int x)
{
//checks whether a number is zero or not
if (x == 0)
return 0;
//true till x is not equal to 1
while( x != 1)
{
//checks whether a number is divisible by 2
if(x % 2 != 0)
return 0;
x /= 2;
}
return 1;
}
Output
[adsense1]
Explanation
In the above program, we have created user-defined function checkPowerofTwo()
to accomplish the task.
Logic of the program is simple i.e. keep dividing the number by 2 iteratively.
Check whether x % 2
is not equal to zero and x
not equal to 1 which indicates x
is not power of 2 otherwise if x
becomes 1 then it is the power of 2.
Logic of the program
If a number is a power of 2, then the bit’s of the previous number will be a complement of the number.
For example:
Bit's of 8 = 1000 Bit's of 7 = 0111
Both are the complement of each other.
So let’s implement this logic.
//C program to check whether a number is power of 2 or not
#include <stdio.h>
int main()
{
int num;
printf("Enter the number you want to test: ");
scanf("%d", &num);
//condition to check whether number is power of two or not
//performing bitwise operation
if((num != 0) && ((num &(num - 1)) == 0))
printf("\n%d is a power of 2", num);
else
printf("\n%d is not a power of 2\n", num);
return 0;
}
Output
Enter the number you want to test: 9 9 is not a power of 2 Enter the number you want to test: 512 512 is a power of 2
Explanation
In the above program, if
condition is used to check whether a number is not equal to zero and it’s previous number is complement or not .