# The shortest code to tell if a number is even or odd

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

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

## 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);}


## 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.

# 48 bytes

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


## 34 bytes

Build with

gcc -nostartfiles -Wl,-ea odd.c

Works in GCC 6.3.0.

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