Header Ads Widget

Ticker

6/recent/ticker-posts

how to check that given number is power of 2 or not

In this article we are going to  learn that how to check that a given number is power of 2 or not .
example :-  2= 2^1
                   4=2^2
                   8= 2^3 and so on .
method 1:-
                   In this method we will check by using log base 2 if ceil and floor of log base of the number is same then number is a power of 2.
          
            ceil(3.56)=4
            ceil(4.23)=5
            floor(3.56)=3
            floor(4.23)=4 
Code:-
#include <stdio.h>
#include<math.h>
int main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
// logic for checking that
// number is power of 2 or not_
if (ceil(log2(n))==floor(log2(n)))
printf("Number is in power of 2");
else
printf("Number is not in power of 2");

return 0;
}

Output:-

Enter a number
8
Number is in power of 2


Method 2:- (keep diving by 2 until n become 1)
                  
 Keep divide the number by 2,  until n becomes 1 ,(i.e, do n = n/2 iteratively). In any iteration, if n%2 becomes non-zero (i.e n is not divisible by 2) and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

Code:-
#include <stdio.h>

int main()
{
int n,r,flag;
printf("Enter a number\n");
scanf("%d",&n);
// logic for checking that
// number is power of 2 or not_
flag=0;
while(n!=1)
{
r=n%2;
if(r!=0)
{
flag=1;
break;
}
n=n/2;
}
if(flag==1)
printf("Number is not power of 2");
else
printf("Number is power of 2");

return 0;
}

Output:-

Enter a number
8
Number is in power of 2



Recommended Post:

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

Key points:-

 MCQs:-


Post a Comment

0 Comments