tags:

views:

228

answers:

4

Possible Duplicate:
How to check if a number is a power of 2

I made the following code but its not working.The compiler gives an error that for missing ) and expression syntax error.I would also like to know how will the operators proceed?From left to right or right to left?

#include <stdio.h>
#include <limits.h>
#include <math.h>
int main()
{
    int i,x=256,y,flag;
    for(i=0,flag=0,y=1;y<INT_MAX;if(flag)break,if(flag)printf("YES"),if(y==x)flag=1,i++,y=pow(2,i));
    return 0;
}
+8  A: 
 bool ispowerof2(unsigned int x) {
   return x && !(x & (x - 1));
 }

Note that the bit pattern of a power of two is of the form 10...0 and that of a number just one less is 011...1.

As far as your code is concerned:

for( i=0, flag=0, y=1;
     y<INT_MAX;      
     if(flag)break,if(flag)printf("YES"),if(y==x)flag=1,i++,y=pow(2,i)
   );

The last part of the for is illegal.

dirkgently
Since he's using `int`s, wouldn't it be better to use them (and skip the special case for 0)?
James Curran
+1 for your logic
mmonem
@James: This'd be an implicit conversion. I see no harm. But why should the special case be skipped?
dirkgently
@james:I dont find anything illegal in my code.I have followed all the rules.
fahad
James Curran
caf
+4  A: 

I'm not going to answer directly, but I'll note that a power of two has only one bit set, and when you subtract one from a number, it clears the least significant bit that's set, and sets all the less significant bits. Looking at one of these fact AND then the other might give an idea of how to detect the first condition in one line.

Jerry Coffin
A: 

With the comma operator, the expressions are evaluated left to right, so your `if(flag)printf("YES") will never be executed.

I'm curious what the point of this is, as (val != 0) && ((val & val-1) == 0) returns non-zero if a value is a power of two.

dash-tom-bang
+1  A: 

Personally, I like this flavor better:

bool isPow2 = ((x & ~(x-1))==x)? x : 0;

It relies on the same binary math, but it handles the case of zero is not a power of 2 in a more subtle way.

abelenky