4
\$\begingroup\$

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 pari if the number is even
  • Output the string dispari if 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

\$\endgroup\$

migrated from stackoverflow.com Oct 9 '12 at 19:56

This question came from our site for professional and enthusiast programmers.

  • 2
    \$\begingroup\$ Is this for C or C++? In C++, that code is invalid. I believe in C as well.\ \$\endgroup\$ – Luchian Grigore Oct 9 '12 at 19:56
  • \$\begingroup\$ @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. \$\endgroup\$ – Vincenzo Pii Oct 9 '12 at 20:01
  • 1
    \$\begingroup\$ Sorry, but your best example doesn't compile with gcc 4.6.3 (Edit: it does) \$\endgroup\$ – Pieter Bos Oct 9 '12 at 20:06
  • 3
    \$\begingroup\$ Slight variation (untested): use return value of scanf to shorten into main(i){puts("dispari"+3*(scanf("%d",&i)&~i));}. \$\endgroup\$ – Howard Oct 9 '12 at 20:12
  • 1
    \$\begingroup\$ You 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"). \$\endgroup\$ – Keith Thompson Oct 10 '12 at 0:40
4
\$\begingroup\$

39 bytes

Given you didn't specified the range of the number input, then here's a solution that handles 0..9 only:

main(){puts("dispari"-~getchar()%2*3);}
\$\endgroup\$
8
\$\begingroup\$

47 bytes (2 less)

main(i){scanf("%d",&i);puts("dispari"-~i%2*3);}

For a positive i, ~i is negative, so ~i%2 is 0 or -1.

\$\endgroup\$
3
\$\begingroup\$

48 bytes

main(i){scanf("%d",&i);puts("dispari"+3-i%2*3);}
\$\endgroup\$
1
\$\begingroup\$

34 bytes

Build with

gcc -nostartfiles -Wl,-ea odd.c

Works in GCC 6.3.0.

a(){puts("dispari"-~getch()%2*3);}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.