This is a challenging problem I came across while I was giving my internship exam in Microsoft. The question goes like this:
User inputs a decimal number. The output should show whether the number is even or odd subject to constraint that only one
printf, and no binary operator, logical operator, arithmetic operator,if-elseandswitch-casecan be used.
So any ideas?
Seth Carnegie’s answer can fail for certain inputs. In particular, on my system, it fails for an input of
2147483647, indicating that it’s even (at least on my system), because converting that value tofloatloses precision.Here’s an improved solution based on his:
The
for (int i = ...syntax is “new” in C99; if your compiler doesn’t support it, declareint i; above the loop.The values to be tested are taken from the command line arguments. It would be easy enough to modify the program so they’re taken from
stdinor elsewhere.The
atoi()function does no error checking, so don’t expect meaningful results if you give it something that’s not a decimal integer.Converting the value of
ntounsigned charbefore passing it tofmod()give a result with the same parity (odd-or-evenness) asn, but that won’t lose precision when converted todouble(that conversion happens implicitly becausefmod()takesdoublearguments). The standard-defined semantics of conversion to an unsigned type are such that this will work correctly even on systems that use a representation other than two’s-complement.It’s just barely possible that converting from
unsigned chartodoublecould lose precision. This would requireunsigned charto have an implausibly large upper bound.doublemust have at least 10 decimal digits of precision, or about 33 or 34 bits; losing precision would requireunsigned charto be at least 34 or so bits (it’s likely I have an off-by-one error or two in there). Such a system could be conforming, but I doubt that any such systems exist in the real world.