Thanks in advance
Regards
Mayur...
This question seems to get asked every couple of weeks.
Consider this: if X is a power of 2, then (X-1) differs from X
in all the bit positions (other than the leading 0's).
--
'The short version of what Walter said is "You have asked a question
which has no useful answer, please reconsider the nature of the
problem you wish to solve".' -- Tony Mantler
http://www.catch22.net/source/snippets.asp
Top of the page
--
Martijn
http://www.sereneconcepts.nl
The answer is "Yes".
(In your problem statement, you state that X is a power of two)
> I need to find it using a Single C statement whether its a power of 2
> or not
If you need to use a single statement, it's not a real problem, it's
homework. So consider _why_ you've been given this homework... would
that be to learn something about copying code from a newsgroup? I think
not.
Richard
/* Gregory Pietsch */
int n_is_Power_of_two(unsigned n)
{
return !(n & n - 1) && n % 1 == 1;
}
int n_is_Power_of_four(unsigned n)
{
return !(n & n - 1) && n % 3 == 1;
}
int n_is_Power_of_eight(unsigned n)
{
return !(n & n - 1) && n % 7 == 1;
}
--
pete
For what unsigned n is n % 1 == 1? ;)
--
Peter
It's part of the sequence:
return !(n & n - 1) && n % 1 == 1
return !(n & n - 1) && n % 3 == 1
However, it seems to be completely wrong. Thank you.
int n_is_Power_of_two(unsigned n)
{
return !(n & n - 1);
}
--
pete
Is 0 a power of two, then?
- jonathan
Not really. Thank you.
int n_is_Power_of_two(unsigned n)
{
return !(n & n - 1) && n != 0;
}
--
pete