A number is in power of 2, when 2 raised to some power is equal to that number.
Is 32 in power of 2? yes
2 raised to power 5 equals 32.
Is 256 in power of 2? yes
2 raised to power 8 equal 256
Is 24 in power of 2? no
In C, header file math.h provide us pow() function
pow(x,y) -- signifies x raised to power y
So we can easily check if number is in power of two
Steps
1.Enter number
2.Set flag=0
3.Set check=0
4.Set i=0
5.loop until check < number
1.check = pow(2,i) [ 2^i]
2. if check equals number then Set flag equal to 1 and break from loop goto step 6
3. increment i = i+1
6.if flag equals to 1 then number is 2 raised to power i
else it is not.
For example
number=4
flag=check=i=0
check< 4 [ 0<4 yes. Go inside loop]
check = pow(2,0) [2^0=1]
check == number [no]
i=i+1 [0+1=1]
check< 4 [ 1<4 yes Go inside loop]
check = pow(2,1) [2^1=2]
check == number [no]
i=i+1 [1+1=2]
check< 4 [ 2<4 yes Go inside loop]
check = pow(2,2) [2^2=4]
check == number [yes] set flag=1, break from loop-goto step 6
is flag == 1 [yes]
print(number is 2 raised to power 2( value of i=2 when we break from loop)
#include<stdio.h>
#include<math.h>
int main()
{
int i, num,check, flag;
printf("\nEnter number:");
scanf("%d",&num);
i=0;
check=0;
flag=0;
while(check<num)
{
check=pow(2,i);
if(check==num)
{
flag++;
break;
}
i++;
}
if(flag==1)
printf("%d is 2 raised to power %d",num,i);
else
printf("Number is not in power of 2 ");
return 0;
}
Is 32 in power of 2? yes
2 raised to power 5 equals 32.
Is 256 in power of 2? yes
2 raised to power 8 equal 256
Is 24 in power of 2? no
In C, header file math.h provide us pow() function
pow(x,y) -- signifies x raised to power y
So we can easily check if number is in power of two
Steps
1.Enter number
2.Set flag=0
3.Set check=0
4.Set i=0
5.loop until check < number
1.check = pow(2,i) [ 2^i]
2. if check equals number then Set flag equal to 1 and break from loop goto step 6
3. increment i = i+1
6.if flag equals to 1 then number is 2 raised to power i
else it is not.
For example
number=4
flag=check=i=0
check< 4 [ 0<4 yes. Go inside loop]
check = pow(2,0) [2^0=1]
check == number [no]
i=i+1 [0+1=1]
check< 4 [ 1<4 yes Go inside loop]
check = pow(2,1) [2^1=2]
check == number [no]
i=i+1 [1+1=2]
check< 4 [ 2<4 yes Go inside loop]
check = pow(2,2) [2^2=4]
check == number [yes] set flag=1, break from loop-goto step 6
is flag == 1 [yes]
print(number is 2 raised to power 2( value of i=2 when we break from loop)
#include<stdio.h>
#include<math.h>
int main()
{
int i, num,check, flag;
printf("\nEnter number:");
scanf("%d",&num);
i=0;
check=0;
flag=0;
while(check<num)
{
check=pow(2,i);
if(check==num)
{
flag++;
break;
}
i++;
}
if(flag==1)
printf("%d is 2 raised to power %d",num,i);
else
printf("Number is not in power of 2 ");
return 0;
}
No comments:
Post a Comment