Even or odd: Difference between revisions
Prolog |
alphabetize - step 1 |
||
Line 990:
isOdd = i % 2 ;isOdd is non-zero if i is odd
isEven = i % 2 ! 1 ;isEven is non-zero if i is even</lang>
=={{header|Python}}==
|
Revision as of 05:20, 13 March 2014
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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.
0815
<lang 0815> }:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65: x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s: </lang>
AutoHotkey
Bitwise ops are probably most efficient: <lang AHK>if ( int & 1 ){ ; do odd stuff }else{ ; do even stuff }</lang>
Ada
<lang ada>-- Ada has bitwise operators in package Interfaces, -- but they work with Interfaces.Unsigned_*** types only. -- Use rem or mod for Integer types, and let the compiler -- optimize it. declare
N : Integer := 5;
begin
if N rem 2 = 0 then Put_Line ("Even number"); elseif N rem 2 /= 0 then Put_Line ("Odd number"); else Put_Line ("Something went really wrong!"); end if;
end;</lang>
Aime
<lang aime>if (x & 1) {
# x is odd
} else {
# x is even
}</lang>
AWK
<lang AWK>function isodd(x) { return (x%2)!=0; }
function iseven(x) { return (x%2)==0; }</lang>
BASIC
<lang basic>10 INPUT "ENTER A NUMBER: ";N 20 IF N/2 <> INT(N/2) THEN PRINT "THE NUMBER IS ODD":GOTO 40 30 PRINT "THE NUMBER IS EVEN" 40 END</lang>
Batch File
<lang dos> @echo off set /p i=Insert number:
- bitwise and
set /a "test1=%i%&1"
- divide last character by 2
set /a test2=%i:~-1%/2
- modulo
set /a test3=%i% %% 2
set test pause>nul </lang>
BBC BASIC
Solutions using AND or MOD are restricted to 32-bit integers, so an alternative solution is given which works with a larger range of values. <lang bbcbasic> IF FNisodd%(14) PRINT "14 is odd" ELSE PRINT "14 is even"
IF FNisodd%(15) PRINT "15 is odd" ELSE PRINT "15 is even" IF FNisodd#(9876543210#) PRINT "9876543210 is odd" ELSE PRINT "9876543210 is even" IF FNisodd#(9876543211#) PRINT "9876543211 is odd" ELSE PRINT "9876543211 is even" END REM Works for -2^31 <= n% < 2^31 DEF FNisodd%(n%) = (n% AND 1) <> 0 REM Works for -2^53 <= n# <= 2^53 DEF FNisodd#(n#) = n# <> 2 * INT(n# / 2)</lang>
Output:
14 is even 15 is odd 9876543210 is even 9876543211 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>
Bracmat
Not the simplest solution, but the cheapest if the number that must be tested has thousands of digits. <lang bracmat>( ( even
= . @( !arg : ? [-2 ( 0 | 2 | 4 | 6 | 8 ) ) )
& (odd=.~(even$!arg)) & ( eventest
= . out $ (!arg is (even$!arg&|not) even) )
& ( oddtest
= . out $ (!arg is (odd$!arg&|not) odd) )
& eventest$5556 & oddtest$5556 & eventest$857234098750432987502398457089435 & oddtest$857234098750432987502398457089435 )</lang> Output:
5556 is even 5556 is not odd 857234098750432987502398457089435 is not even 857234098750432987502398457089435 is odd
Brainf***
Assumes that input characters are an ASCII representation of a valid integer. Output is input mod 2. <lang bf>,[>,----------] Read until newline ++< Get a 2 and move into position [->-[>+>>]> Do [+[-<+>]>+>>] divmod <<<<<] magic >[-]<++++++++ Clear and get an 8 [>++++++<-] to get a 48 >[>+<-]>. to get n % 2 to ASCII and print</lang>
If one need only determine rather than act on the parity of the input, the following is sufficient; it terminates either quickly or never. <lang bf>,[>,----------]<[--]</lang>
Burlesque
<lang burlesque>2.%</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.
C++
Test using the modulo operator, or use the c example from above. <lang cpp>bool isEven(int Value){
if((x % 2) == 0){ return true; } return false;
} </lang>
C#
<lang csharp>namespace RosettaCode {
using System;
public static class EvenOrOdd { public static bool IsEvenBitwise(this int number) { return (number & 1) == 0; }
public static bool IsOddBitwise(this int number) { return (number & 1) != 0; }
public static bool IsEvenRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder == 0; }
public static bool IsOddRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder != 0; }
public static bool IsEvenModulo(this int number) { return (number % 2) == 0; }
public static bool IsOddModulo(this int number) { return (number % 2) != 0; } }
}</lang>
Clojure
Standard predicates: <lang clojure>(if (even? some-var) (do-even-stuff)) (if (odd? some-var) (do-odd-stuff))</lang>
COBOL
<lang cobol> IF FUNCTION REM(Num, 2) = 0
DISPLAY Num " is even." ELSE DISPLAY Num " is odd." END-IF</lang>
Common Lisp
Standard predicates: <lang lisp>(if (evenp some-var) (do-even-stuff)) (if (oddp some-other-var) (do-odd-stuff))</lang>
Component Pascal
BlackBox Component Builder <lang oberon2> MODULE EvenOdd; IMPORT StdLog,Args,Strings;
PROCEDURE BitwiseOdd(i: INTEGER): BOOLEAN; BEGIN RETURN 0 IN BITS(i) END BitwiseOdd;
PROCEDURE Odd(i: INTEGER): BOOLEAN; BEGIN RETURN (i MOD 2) # 0 END Odd;
PROCEDURE CongruenceOdd(i: INTEGER): BOOLEAN; BEGIN RETURN ((i -1) MOD 2) = 0 END CongruenceOdd;
PROCEDURE Do*;
VAR
p: Args.Params;
i,done,x: INTEGER;
BEGIN
Args.Get(p);
StdLog.String("Builtin function: ");StdLog.Ln;i := 0;
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
IF ODD(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
END;
StdLog.String("Bitwise: ");StdLog.Ln;i:= 0;
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
IF BitwiseOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
END;
StdLog.String("Module: ");StdLog.Ln;i := 0;
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
IF Odd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
END;
StdLog.String("Congruences: ");StdLog.Ln;i := 0;
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
IF CongruenceOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
END;
END Do;
</lang>
Execute: ^Q EvenOdd.Do 10 11 0 57 34 -23 -42~
Output:
Builtin function: 10 is:> even 11 is:> odd 0 is:> even 57 is:> odd 34 is:> even -23 is:> odd -42 is:> even Bitwise: 10 is:> even 11 is:> odd 0 is:> even 57 is:> odd 34 is:> even -23 is:> odd -42 is:> even Module: 10 is:> even 11 is:> odd 0 is:> even 57 is:> odd 34 is:> even -23 is:> odd -42 is:> even Congruences: 10 is:> even 11 is:> odd 0 is:> even 57 is:> odd 34 is:> even -23 is:> odd -42 is:> even
D
<lang d>import std.stdio, std.bigint;
void main() {
foreach (i; -5 .. 6) writeln(i, " ", i & 1, " ", i % 2, " ", BigInt(i) % 2);
}</lang>
- Output:
-5 1 -1 -1 -4 0 0 0 -3 1 -1 -1 -2 0 0 0 -1 1 -1 -1 0 0 0 0 1 1 1 1 2 0 0 0 3 1 1 1 4 0 0 0 5 1 1 1
Déjà Vu
<lang dejavu>even n:
= 0 % n 2
odd:
not even
!. odd 0 !. even 0 !. odd 7 !. even 7 </lang>
- Output:
false true true false
DWScript
Predicate: <lang delphi>var isOdd := Odd(i);</lang> Bitwise and: <lang delphi>var isOdd := (i and 1)<>0;</lang> Modulo: <lang delphi>var isOdd := (i mod 2)=1;</lang>
Erlang
Using Division by 2 Method
<lang erlang>%% Implemented by Arjun Sunel -module(even_odd). -export([main/0]).
main()-> test(8).
test(N) -> if (N rem 2)==1 -> io:format("odd\n"); true -> io:format("even\n") end. </lang>
Using the least-significant bit method
<lang erlang> %% Implemented by Arjun Sunel -module(even_odd2). -export([main/0]).
main()-> test(10).
test(N) -> if (N band 1)==1 -> io:format("odd\n"); true -> io:format("even\n") end. </lang>
Euphoria
Using standard function <lang Euphoria> include std/math.e
for i = 1 to 10 do
? {i, is_even(i)}
end for </lang> Output
{1,0} {2,1} {3,0} {4,1} {5,0} {6,1} {7,0} {8,1} {9,0} {10,1}
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
Fish
This example assumes that the input command i returns an integer when one was inputted and that the user inputs a valid positive integer terminated by a newline. <lang Fish><v"Please enter a number:"a
>l0)?!vo v < v o<
^ >i:a=?v>i:a=?v$a*+^>"The number is even."ar>l0=?!^>
> >2%0=?^"The number is odd."ar ^</lang>
The actual computation is the 2%0= part. The rest is either user interface or parsing input.
Forth
<lang forth>: odd? ( n -- ? ) 1 and ;</lang>
Fortran
Please find the compilation and example run in the comments at the beginning of the FORTRAN 2008 source. Separating the bit 0 parity module from the main program enables reuse of the even and odd functions. Even and odd, with scalar and vector interfaces demonstrate the generic function capability of FORTRAN 90. Threading, stdin, and all-intrinsics are vestigial and have no influence here other than to confuse you. <lang FORTRAN> !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Tue May 21 20:22:56 ! !a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt !gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f ! n odd even !-6 F T !-5 T F !-4 F T !-3 T F !-2 F T !-1 T F ! 0 F T ! 1 T F ! 2 F T ! 3 T F ! 4 F T ! 5 T F ! 6 F T ! -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 n ! F T F T F T F T F T F T F odd ! T F T F T F T F T F T F T even ! !Compilation finished at Tue May 21 20:22:56
module bit0parity
interface odd module procedure odd_scalar, odd_list end interface
interface even module procedure even_scalar, even_list end interface
contains
logical function odd_scalar(a) implicit none integer, intent(in) :: a odd_scalar = btest(a, 0) end function odd_scalar
logical function even_scalar(a) implicit none integer, intent(in) :: a even_scalar = .not. odd_scalar(a) end function even_scalar
function odd_list(a) result(rv) implicit none integer, dimension(:), intent(in) :: a logical, dimension(size(a)) :: rv rv = btest(a, 0) end function odd_list
function even_list(a) result(rv) implicit none integer, dimension(:), intent(in) :: a logical, dimension(size(a)) :: rv rv = .not. odd_list(a) end function even_list
end module bit0parity
program oe
use bit0parity implicit none integer :: i integer, dimension(13) :: j write(6,'(a2,2a8)') 'n', 'odd', 'even' write(6, '(i2,2l5)') (i, odd_scalar(i), even_scalar(i), i=-6,6) do i=-6, 6 j(i+7) = i end do write(6, '((13i3),a8/(13l3),a8/(13l3),a8)') j, 'n', odd(j), 'odd', even(j), 'even'
end program oe </lang>
F#
Bitwise and: <lang fsharp>let isEven x =
x &&& 1 = 0</lang>
Modulo: <lang fsharp>let isEven x =
x % 2 = 0</lang>
GAP
<lang gap>IsEvenInt(n); IsOddInt(n);</lang>
Go
<lang go>package main
import (
"fmt" "math/big"
)
func main() {
test(-2) test(-1) test(0) test(1) test(2) testBig("-222222222222222222222222222222222222") testBig("-1") testBig("0") testBig("1") testBig("222222222222222222222222222222222222")
}
func test(n int) {
fmt.Printf("Testing integer %3d: ", n) // & 1 is a good way to test if n&1 == 0 { fmt.Print("even ") } else { fmt.Print(" odd ") } // Careful when using %: negative n % 2 returns -1. So, the code below // works, but can be broken by someone thinking they can reverse the // test by testing n % 2 == 1. The valid reverse test is n % 2 != 0. if n%2 == 0 { fmt.Println("even") } else { fmt.Println(" odd") }
}
func testBig(s string) {
b, _ := new(big.Int).SetString(s, 10) fmt.Printf("Testing big integer %v: ", b) // the Bit function is the only sensible test for big ints. if b.Bit(0) == 0 { fmt.Println("even") } else { fmt.Println("odd") }
}</lang>
- Output:
Testing integer -2: even even Testing integer -1: odd odd Testing integer 0: even even Testing integer 1: odd odd Testing integer 2: even even Testing big integer -222222222222222222222222222222222222: even Testing big integer -1: odd Testing big integer 0: even Testing big integer 1: odd Testing big integer 222222222222222222222222222222222222: even
Groovy
Solution: <lang groovy>def isOdd = { int i -> (i & 1) as boolean } def isEven = {int i -> ! isOdd(i) }</lang> Test: <lang groovy>1.step(20, 2) { assert isOdd(it) }
50.step(-50, -2) { assert isEven(it) }</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>
JavaScript
Modulo: <lang javascript>function isEven( i ) {
return i % 2 === 0;
} </lang>
Julia
Built-in functions: <lang julia>iseven(i), isodd(i)</lang>
LabVIEW
Using bitwise And
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lang5
<lang lang5>: even? 2 % not ;
- odd? 2 % ;
1 even? . # 0 1 odd? . # 1</lang>
==Liberty BASIC ==<lang lb> n=12
if n mod 2 = 0 then print "even" else print "odd"</lang>
Lasso
<lang Lasso>define isoddoreven(i::integer) => { #i % 2 ? return 'odd' return 'even' } isoddoreven(12)</lang>
Logtalk
<lang logtalk>
- - object(even_odd).
:- public(test_mod/1). test_mod(I) :- ( I mod 2 =:= 0 -> write(even), nl ; write(odd), nl ).
:- public(test_bit/1). test_bit(I) :- ( I /\ 1 =:= 1 -> write(odd), nl ; write(even), nl ).
- - end_object.
</lang> Output: <lang text> | ?- even_odd::test_mod(1). odd yes
| ?- even_odd::test_mod(2). even yes
| ?- even_odd::test_bit(1). odd yes
| ?- even_odd::test_bit(2). even yes </lang>
Lua
<lang lua>-- test for even number if n % 2 == 0 then
print "The number is even"
end
-- test for odd number if not (n % 2 == 0) then
print "The number is odd"
end</lang>
Mathematica
<lang Mathematica>EvenQ[8]</lang>
MATLAB / Octave
Bitwise And: <lang Matlab> isOdd = logical(bitand(N,1));
isEven = ~logical(bitand(N,1)); </lang>
Remainder of division by two <lang Matlab> isOdd = logical(rem(N,2));
isEven = ~logical(rem(N,2)); </lang>
Modulo: 2 <lang Matlab> isOdd = logical(mod(N,2));
isEven = ~logical(mod(N,2)); </lang>
Maxima
<lang maxima>evenp(n); oddp(n);</lang>
Mercury
Mercury's 'int' module provides tests for even/odd, along with all the operators that would be otherwise used to implement them. <lang Mercury>even(N) % in a body, suceeeds iff N is even. odd(N). % in a body, succeeds iff N is odd.
% rolling our own:
- - pred even(int::in) is semidet.
% It's an error to have all three in one module, mind; even/1 would fail to check as semidet. even(N) :- N mod 2 = 0. % using division that truncates towards -infinity even(N) :- N rem 2 = 0. % using division that truncates towards zero even(N) :- N /\ 1 = 0. % using bit-wise and.</lang>
МК-61/52
<lang>/ 2 {x} ЗН</lang>
Result: "0" - number is even; "1" - number is odd.
NetRexx
<lang NetRexx>/* 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)
</lang> Output:
Val: mod - ver - pos - bits ---: ---- + ---- + ---- + ---- -15: Odd - Odd - Odd - Odd -12: Even - Even - Even - Even -9: Odd - Odd - Odd - Odd -6: Even - Even - Even - Even -3: Odd - Odd - Odd - Odd 0: Even - Even - Even - Even 3: Odd - Odd - Odd - Odd 6: Even - Even - Even - Even 9: Odd - Odd - Odd - Odd 12: Even - Even - Even - Even 15: Odd - Odd - Odd - Odd
Objeck
<lang objeck>a := Console->ReadString()->ToInt(); if(a % 2 = 0) {
"even"->PrintLine();
} else {
"odd"->PrintLine();
};</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.
Pascal
Built-in boolean function odd: <lang pascal>isOdd := odd(someIntegerNumber);</lang> bitwise and: <lang pascal>function isOdd(Number: integer): boolean begin
isOdd := boolean(Number and 1)
end;</lang> Dividing and multiplying by 2 and test on equality: <lang pascal>function isEven(Number: integer): boolean begin
isEven := (Number = ((Number div 2) * 2))
end;</lang> Using built-in modulo <lang pascal>function isOdd(Number: integer): boolean begin
isOdd := boolean(Number mod 2)
end;</lang>
Perl
<lang perl>for(0..10){
print "$_ is ", qw(even odd)[$_ % 2],"\n";
}</lang> or <lang perl>print 6 % 2 ? 'odd' : 'even'; # prints even</lang>
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>
PHP
<lang php> // using bitwise and to check least significant digit echo (2 & 1) ? 'odd' : 'even'; echo (3 & 1) ? 'odd' : 'even';
// using modulo echo (3 % 2) ? 'odd' : 'even'; echo (4 % 2) ? 'odd' : 'even'; </lang>
- Output:
even odd odd even
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>
PL/I
<lang PL/I>i = iand(i,1)</lang> The result is 1 when i is odd, and 0 when i is even.
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
Python: Using the least-significant bit method
<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>
Python: Using modular congruences
<lang python>>> def is_even(i):
return (i % 2) == 0
>>> is_even(1) False >>> is_even(2) True >>></lang>
R
<lang R>is.even <- function(x) !is.odd(x)
is.odd <- function(x) intToBits(x)[1] == 1
- or
is.odd <- function(x) x %% 2 == 1</lang>
Racket
With built in predicates: <lang Racket>(even? 6) ; -> true (even? 5) ; -> false (odd? 6) ; -> false (odd? 5) ; -> true </lang>
With modular arithmetic: <lang Racket>(define (my-even? x)
(= (modulo x 2) 0))
(define (my-odd? x)
(= (modulo x 2) 1))</lang>
Rascal
<lang rascal>public bool isEven(int n) = (n % 2) == 0; public bool isOdd(int n) = (n % 2) == 1;</lang> Or with block quotes: <lang rascal>public bool isEven(int n){return (n % 2) == 0;} public bool isOdd(int n){return (n % 2) == 1;}</lang>
REXX
<lang rexx>/*REXX program displays if an integer is even or odd. */ numeric digits 1000 /*handle most big 'uns from the CL*/ parse arg x _ . /*get arg(s) from the command line*/ if x== then call terr 'no input' if _\== | arg()\==1 then call terr 'too many arguments:' arg(1) if \datatype(x,'N') then call terr x "isn't numeric" if \datatype(x,'W') then call terr x "isn't an integer" y=abs(x) /*just in case X is negative, */
/*(modulus of neg # might be -1), */
/*══════════════════════════════════════════════════════════════════════*/
say center('test using modulo method',40,'─')
if y//2 then say x 'is odd'
else say x 'is even'
/*══════════════════════════════════════════════════════════════════════*/ say; say center('test rightmost digit for evenness',40,'─') _=right(y,1) if pos(_,02468)==0 then say x 'is odd'
else say x 'is even'
/*══════════════════════════════════════════════════════════════════════*/ say; say center('test rightmost digit for oddness',40,'─') if pos(right(y,1),13579)==0 then say x 'is even'
else say x 'is odd'
/*══════════════════════════════════════════════════════════════════════*/ say; say center('test rightmost (binary) bit',40,'─')
/*Note: some REXX's don't have a D2B bif.*/
if right(x2b(d2x(y)),1) then say x 'is odd'
else say x 'is even'
/*══════════════════════════════════════════════════════════════════════*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────TERR subroutine─────────────────────*/ terr: say; say '***error!***'; say; say arg(1); say; exit 13</lang> output when using the input of 0
─────────────modulo method────────────── 0 is even ───test rightmost digit for evenness──── 0 is even ────test rightmost digit for oddness──── 0 is even ──────test rightmost (binary) bit─────── 0 is even
out0put when using the input of: 9876543210987654321098765432109876543210987654321
─────────────modulo method────────────── 9876543210987654321098765432109876543210987654321 is odd ───test rightmost digit for evenness──── 9876543210987654321098765432109876543210987654321 is odd ────test rightmost digit for oddness──── 9876543210987654321098765432109876543210987654321 is odd ──────test rightmost (binary) bit─────── 9876543210987654321098765432109876543210987654321 is odd
output when using the input of 00067.00
────────test using modulo method──────── 00067.00 is odd ───test rightmost digit for evenness──── 00067.00 is odd ────test rightmost digit for oddness──── 00067.00 is odd ──────test rightmost (binary) bit─────── 00067.00 is odd
output when using the input of: -9411
─────────────modulo method────────────── -9411 is odd ───test rightmost digit for evenness──── -9411 is odd ────test rightmost digit for oddness──── -9411 is odd ──────test rightmost (binary) bit─────── -9411 is odd
Ruby
Ruby 1.8.7 added Integer#even? and Integer#odd? as new methods.
<lang ruby>print "evens: " p -5.upto(5).select {|n| n.even?} print "odds: " p -5.upto(5).select {|n| n.odd?}</lang>
- Output:
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
- The next way only works when n.to_f/2 is exact.
- If Float is IEEE double, then -2**53 .. 2**53 must include n.
n.to_f/2 == n/2
- You can use the bracket operator to access the i'th bit
- of a Fixnum or Bignum (i = 0 means least significant bit)
n[0].zero?</lang>
Run BASIC
<lang runbasic>for i = 1 to 10
if i and 1 then print i;" is odd" else print i;" is even"
next i</lang>
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
Scala
<lang scala>def isEven( v:Int ) : Boolean = v % 2 == 0 def isOdd( v:Int ) : Boolean = v % 2 != 0</lang> Accept any numeric type as an argument: <lang scala>def isEven( v:Number ) : Boolean = v.longValue % 2 == 0 def isOdd( v:Number ) : Boolean = v.longValue % 2 != 0</lang>
- Output:
isOdd( 81 ) // Results in true isEven( BigInt(378) ) // Results in true isEven( 234.05003513013145 ) // Results in true
Scheme
even?
and odd?
functions are built-in (R4RS, R5RS, and R6RS):
<lang scheme>> (even? 5)
- f
> (even? 42)
- t
> (odd? 5)
- t
> (odd? 42)
- f</lang>
Seed7
Test whether an integer or bigInteger is odd: <lang seed7>odd(aNumber)</lang> Test whether an integer or bigInteger is even: <lang seed7>not odd(aNumber)</lang>
Smalltalk
Using the built in methods on Number class:
<lang smalltalk>5 even 5 odd</lang>
even is implemented as follows: <lang smalltalk>Number>>even ^((self digitAt: 1) bitAnd: 1) = 0 </lang>
SNUSP
<lang SNUSP> $====!/?\==even#
- -
- odd==\?/
</lang>
Tcl
<lang tcl>package require Tcl 8.5
- 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
XPL0
<lang XPL0>include c:\cxpl\codes; int I; [for I:= -4 to +3 do
[IntOut(0, I); Text(0, if I&1 then " is odd " else " is even "); Text(0, if rem(I/2)#0 then "odd" else "even"); CrLf(0); ];
]</lang>
Output:
-4 is even even -3 is odd odd -2 is even even -1 is odd odd 0 is even even 1 is odd odd 2 is even even 3 is odd odd
zkl
<lang zkl>[-3..4].pump(fcn(n){println(n," is ",n.isEven and "even" or "odd")})</lang> Ints have isEven and isOdd properties
- Output:
-3 is odd -2 is even -1 is odd 0 is even 1 is odd 2 is even 3 is odd 4 is even
- Programming Tasks
- Solutions by Programming Task
- 0815
- AutoHotkey
- Ada
- Aime
- AWK
- BASIC
- Batch File
- BBC BASIC
- Bc
- Bracmat
- Brainf***
- Burlesque
- C
- C++
- C sharp
- Clojure
- COBOL
- Common Lisp
- Component Pascal
- D
- Déjà Vu
- DWScript
- Erlang
- Euphoria
- Factor
- Fish
- Forth
- Fortran
- F Sharp
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Julia
- LabVIEW
- Lang5
- Liberty BASIC
- Lasso
- Logtalk
- Lua
- Mathematica
- MATLAB
- Octave
- Maxima
- Mercury
- МК-61/52
- NetRexx
- Objeck
- OCaml
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PureBasic
- Python
- R
- Racket
- Rascal
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Smalltalk
- SNUSP
- Tcl
- TUSCRIPT
- XPL0
- Zkl