Even or odd: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Ruby}}: Integer#even? and Integer#odd? are new to 1.8.7 (source: ruby/doc/NEWS-1.8.7). Float must be exact.)
No edit summary
Line 69: Line 69:
Prelude> odd 42
Prelude> odd 42
False</lang>
False</lang>

=={{header|Icon}} and {{header|Unicon}}==
One way is to check the remainder:
<lang unicon>procedure isEven(n)
return n%2 = 0
end</lang>


=={{header|J}}==
=={{header|J}}==

Revision as of 03:00, 2 December 2011

Task
Even or odd
You are encouraged to solve this task according to the task description, using any language you may know.

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 compares a 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>

C

Test by bitwise and'ing 1, works for any builtin integer type as long as it's 2's compliment (it's always so nowadays): <lang c>if (x & 1) {

   /* x is odd */

} else {

   /* or not */

}</lang> If using long integer type from GMP (mpz_t), there are provided macros: <lang c>mpz_t x; ... if (mpz_even_p(x)) { /* x is even */ } if (mpz_odd_p(x)) { /* x is odd */ }</lang> The macros evaluate x more than once, so it should not be something with side effects.

Common Lisp

Standard predicates: <lang lisp>(if (evenp some-var) (do-even-stuff)) (if (oddp some-other-var) (do-odd-stuff))</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

Forth

<lang forth>: odd? ( n -- ? ) 1 and ;</lang>

Haskell

even and odd functions are already included in the standard Prelude.

<lang haskell>Prelude> even 5 False Prelude> even 42 True Prelude> odd 5 True Prelude> odd 42 False</lang>

Icon and Unicon

One way is to check the remainder: <lang unicon>procedure isEven(n)

   return n%2 = 0

end</lang>

J

Modulo:

<lang j> 2 | 2 3 5 7 0 1 1 1

  2|2 3 5 7 + (2^89x)-1

1 0 0 0</lang>

Remainder:

<lang j> (= <.&.-:) 2 3 5 7 1 0 0 0

  (= <.&.-:) 2 3 5 7+(2^89x)-1

0 1 1 1</lang>

Last bit in bit representation: <lang j> {:"1@#: 2 3 5 7 0 1 1 1

  {:"1@#: 2 3 5 7+(2^89x)-1

1 0 0 0</lang>

Bitwise and:

<lang j> 1 (17 b.) 2 3 5 7 0 1 1 1</lang>

Note: as a general rule, the simplest expressions in J should be preferred over more complex approaches.

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 (even works for negative numbers because of the way BigInteger represents the bits of numbers): <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>

OCaml

Modulo:

<lang ocaml>let is_even d =

 (d mod 2) = 0

let is_odd d =

 (d mod 2) <> 0</lang>

Bitwise and:

<lang ocaml>let is_even d =

 (d land 1) = 0

let is_odd d =

 (d land 1) <> 0</lang>

PARI/GP

GP does not have a built-in predicate for testing parity, but it's easy to code: <lang parigp>odd(n)=n%2;</lang> Alternately: <lang parigp>odd(n)=bitand(n,1);</lang>

PARI can use the same method as C for testing individual words. For multiprecision integers (t_INT), use mpodd. If the number is known to be nonzero, mod2 is (insignificantly) faster.

Perl 6

Perl 6 doesn't have a built-in for this, but with subsets it's easy to define a predicate for it. <lang perl6>subset Even of Int where * %% 2; subset Odd of Int where * % 2;

say 1 ~~ Even; # false say 1 ~~ Odd; # true say 1.5 ~~ Odd # false ( 1.5 is not an Int )</lang>

PicoLisp

PicoLisp doesn't have a built-in predicate for that. Using 'bit?' is the easiest and most efficient. The bit test with 1 will return NIL if the number is even. <lang PicoLisp>: (bit? 1 3) -> 1 # Odd

(bit? 1 4)

-> NIL # Even</lang>

Pike

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

PureBasic

<lang PureBasic>;use last bit method isOdd = i & 1 ;isOdd is non-zero if i is odd isEven = i & 1 ! 1 ;isEven is non-zero if i is even

use modular method

isOdd = i % 2 ;isOdd is non-zero if i is odd isEven = i % 2 ! 1 ;isEven is non-zero if i is even</lang>

Python

<lang python>>>> def is_odd(i): return bool(i & 1)

>>> def is_even(i): return not is_odd(i)

>>> [(j, is_odd(j)) for j in range(10)] [(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)] >>> [(j, is_even(j)) for j in range(10)] [(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)] >>> </lang>

Ruby

Ruby 1.8.7 added Integer#even? and Integer#odd? as new methods.

Works with: Ruby version 1.8.7

<lang ruby>print "evens: " p -5.upto(5).select {|n| n.even?} print "odds: " p -5.upto(5).select {|n| n.odd?}</lang>

outputs

evens: [-4, -2, 0, 2, 4]
odds: [-5, -3, -1, 1, 3, 5]

Other ways to test even-ness: <lang ruby>n & 1 == 0 quotient, remainder = n.divmod(2); remainder == 0

  1. The next way only works when n.to_f/2 is exact.
  2. If Float is IEEE double, then -2**53 .. 2**53 must include n.

n.to_f/2 == n/2</lang>

Tcl

<lang tcl>package require Tcl 8.5

  1. Bitwise test is the most efficient

proc tcl::mathfunc::isOdd x { expr {$x & 1} } proc tcl::mathfunc::isEven x { expr {!($x & 1)} }

puts " # O E" puts 24:[expr isOdd(24)],[expr isEven(24)] puts 49:[expr isOdd(49)],[expr isEven(49)]</lang> Output:

 # O E
24:0,1
49:1,0

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT LOOP n=-5,5 x=MOD(n,2) SELECT x CASE 0 PRINT n," is even" DEFAULT PRINT n," is odd" ENDSELECT ENDLOOP </lang> Output:

-5 is odd
-4 is even
-3 is odd
-2 is even
-1 is odd
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd