4
1
One of my colleagues proposed us a challenge: to write the shortest C/C++ program to determine if a number is even or odd.
These are the requirements:
- Get a number from keyboard, at run-time (not from command line)
- Output the string
pariif the number is even - Output the string
dispariif the number is odd - We can assume that the input is legal
- We can assume that the machine has a i386 architecture
- Code preprocessing is not allowed (e.g.: use
#defines) - [edit after comments] The code can be considered valid if it compiles with
gcc 4.x
This is the best attempt we had so far (file test.c, 50B):
main(i){scanf("%d",&i);puts("dispari"+3*(~i&1));}
Do you think we can go further?
(*): "dispari" is the italian for odd and "pari" is the italian for even
2Is this for C or C++? In C++, that code is invalid. I believe in C as well.\ – Luchian Grigore – 2012-10-09T19:56:03.823
@LuchianGrigore, you can use both C and C++. The choice depends on the language that lets you write the shortest code. The code above compiles correctly with gcc, maybe I should add that as a requirement. – Vincenzo Pii – 2012-10-09T20:01:42.300
1Sorry, but your best example doesn't compile with gcc 4.6.3 (Edit: it does) – Pieter Bos – 2012-10-09T20:06:04.260
@niomaster, I have the same version and it works, but not if the file extension is different than
.c. Anyway, if you think that doesn't work, you could try providing your shortest working solution :). – Vincenzo Pii – 2012-10-09T20:07:04.4133Slight variation (untested): use return value of
scanfto shorten intomain(i){puts("dispari"+3*(scanf("%d",&i)&~i));}. – Howard – 2012-10-09T20:12:55.970@Howard that works with gcc 4.6.3! – Vincenzo Pii – 2012-10-09T20:17:56.117
@Jack, my solution is C, yours could be C++, hence the tag. We are not interested in warnings here, this is just a stupid competition between too nerdish colleagues! – Vincenzo Pii – 2012-10-09T20:52:51.427
@VincenzoPii: Ok. Removed comment. I'm sorry, I'm in the sense of
stackoverflow.com. – Jack – 2012-10-09T21:51:44.7531You can't legally and portably perform output without either
#include <stdio.h>(which is a preprocessor directive) or your own declaration of the routines you're using. As of C90, calling an undeclared function has defined behavior only in narrow circumstances; as of C99, it's a constraint violation (C's version of "illegal"). – Keith Thompson – 2012-10-10T00:40:31.503Why no other languages allowed?! I like Perl so much ._.
print<><0?dis:$,,pari– Leo Pflug – 2014-02-13T10:07:24.150