Task

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.


/* NetRexx */
options replace format comments java crossref symbols nobinary
 
say 'Val'.right(5)': mod  - ver  - pos  - bits'
say '---'.right(5)': ---- + ---- + ---- + ----'
loop nn = -15 to 15 by 3
  say nn.right(5)':' eo(isEven(nn)) '-' eo(isEven(nn, 'v')) '-' eo(isEven(nn, 'p')) '-' eo(isEven(nn, 'b'))
  end nn
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Overloaded method.  Default is to use the remainder specialization below
method isEven(anInt, meth = 'R') public static returns boolean
  select case meth.upper().left(1)
    when 'R' then eo = isEvenRemainder(anInt)
    when 'V' then eo = isEvenVerify(anInt)
    when 'P' then eo = isEvenPos(anInt)
    when 'B' then eo = isEvenBits(anInt)
    otherwise     eo = isEvenRemainder(anInt) -- default
    end
  return eo
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenRemainder(anInt) public static returns boolean
  return anInt // 2 == 0
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenVerify(anInt) public static returns boolean
  return anInt.right(1).verify('02468') == 0
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenPos(anInt) public static returns boolean
  return '13579'.pos(anInt.right(1)) == 0
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenBits(anInt) public static returns boolean
  return \(anInt.d2x(1).x2b().right(1))
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method eo(state = boolean) public static
  if state then sv = 'Even'
           else sv = 'Odd'
  return sv.left(4)
 