exactly... if x=0, then the expression will give 0 as the result indicating that 0 is a power of 2 which it is not.. thatz why the expression checks for (x != 0)
//include math.h void main() { int n,logval,powval; printf("Enter a number to find whether it is s power of 2\n"); scanf("%d",&n); logval=log(n)/log(2); powval=pow(2,logval); if(powval==n) printf("The number is a power of 2"); else printf("The number is not a power of 2"); getch(); }
8 comments:
think it can be made simpler with xor(hasa to think)
give it a try ...
y do u check x!=0, if x=0, x-1 = -1 which will be represented as 11111111 which when ANDed with 00000000 will again give 0 :-)
exactly... if x=0, then the expression will give 0 as the result indicating that 0 is a power of 2 which it is not.. thatz why the expression checks for (x != 0)
example: 0x80000000
this is the number -2147483648...
we all know that no negative number is a power of 2
//include math.h
void main()
{
int n,logval,powval;
printf("Enter a number to find whether it is s power of 2\n");
scanf("%d",&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf("The number is a power of 2");
else
printf("The number is not a power of 2");
getch();
}
udhaya u can't use loops u need to solve without the loop
Post a Comment