Even or odd

From Rosetta Code
Even or odd is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Test whether an integer is even or odd.

There is more than one way to solve this task:

  • Use the even and odd predicates, if the language provides them.
  • Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
  • Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
  • Use modular congruences:
    • i ≡ 0 (mod 2) iff i is even.
    • i ≡ 1 (mod 2) iff i is odd.

bc

There are no bitwise operations, so this solution remainder with zero. Calculation of i % 2 only works when scale = 0.

<lang bc>i = -3

/* Assumes that i is an integer. */ scale = 0 if (i % 2 == 0) "i is even " if (i % 2) "i is odd "</lang>

Factor

The math vocabulary provides even? and odd? predicates. This example runs at the listener, which already uses the math vocabulary.

( scratchpad ) 20 even? .
t
( scratchpad ) 35 even? .
f
( scratchpad ) 20 odd? .
f
( scratchpad ) 35 odd? .
t

Java

Bitwise and: <lang java>public static boolean isEven(int i){

   return (i & 1) == 0;

}</lang> Modulo: <lang java>public static boolean isEven(int i){

   return (i % 2) == 0;

}</lang> Arbitrary precision bitwise: <lang java>public static boolean isEven(BigInteger i){

   return (i.and(BigInteger.ONE)).equals(BigInteger.ZERO);

}</lang> Arbitrary precision bit test: <lang java>public static boolean isEven(BigInteger i){

   return i.testBit(0);

}</lang> Arbitrary precision modulo: <lang java>public static boolean isEven(BigInteger i){

   return (i.mod(BigInteger.valueOf(2))).equals(BigInteger.ZERO);

}</lang>

Pike

<lang Pike>> int i = 73; > (i&1); Result: 1 > i%2; Result: 1</lang>