3

Ways of rewriting this code more efficiently and/or shortly to save bytes and appear less verbose?

if(N % 2 == 0 && (N == 6 || N == 8 || N == 10 || N == 12 || N == 14 || N== 16 || N == 18 || N == 20 ))
{
    printf("Weird\n");
}

Given the language is C, although doesn't matter if its java or php or any other language :-).

yousafe007
  • 119
  • 1
  • 8

3 Answers3

10

Why won't you just do :

if (N % 2 == 0 && (N >= 6 && N <= 20))
{
     /* ... */
}
5

Given N is unsigned integer.

if(N % 2 == 0 && (N-6) <= 14)
{
    printf("Weird\n");
}
Anton Angelov
  • 1,223
  • 7
  • 19
5

Supposing that N has an unsigned integral type, and you are more interested minimal source code than in clarity, then you might write

if (((N - 6) & 14) + 6 == N) {
    printf("Weird\n");
}

Explanation:

The first operation, N - 6, shifts the range of the acceptable values from 6 - 20 to 0 - 14. The latter range can be expressed with four bits.

The second operation, & 14, is a bitwise and with bit pattern 1110. That will leave even numbers in the range 0 - 14 unchanged, but it will convert odd numbers to even and it will clear any higher bits. The only values that survive unchanged are the ones derived from the original target values in the first step.

The third operation reverses the first, so that the result can be compared directly with the original number. If the combined sequence of operations reproduces the original number, then that number is one of the ones you were looking for.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157