how would you decide a number is some power of 2 in c? no loops are allowed and this should be done in one statement.
Printable View
how would you decide a number is some power of 2 in c? no loops are allowed and this should be done in one statement.
LaitinenCode:bool IsPowerOfTwo (int number)
{
return number ? ((number & -number)==number):false;
}
double SomeNumber, SomeExponent;
SomeNumber = 2**SomeExponent;
log(SomeNumber) = SomeExponent * log(2);
SomeExponent = log(SomeNumber) / log(2);
is SomeExponent an integer?
in theory:
if SomeExponent - floor(SomeExponent) = 0;
in practice:
double epsilon;
epsilon = .00001;
if abs( SomeExponent - floor(SomeExponent) ) < epsilon;
Pretty cool solution Latinen.
Folks, we should be determining that this is not a homework question, or that the OP has at least attempted it, before answering. The form of the OP certainly suggests that it is.
For integers, there's an even simpler solution.Quote:
Originally Posted by S_M_A
(ETA: I suppose I should say conceptually simpler...)
let me remove my codes. :)
Note that it's always the person with only 1 or 2 posts that asks these kind of questions.Quote:
Originally Posted by RAJJUMOTE
Definitely a homework question, since the OP has not appeared since he now has something to take back to the teacher. We should be much better sniffing out "do my homework" posts, and not provide answers.
Regards,
Paul McKenzie
See signature below... :D :D :DQuote:
Originally Posted by Paul McKenzie