Even or odd: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Diego}}: Added Diego entry)
 
(42 intermediate revisions by 26 users not shown)
Line 1: Line 1:
{{task}}
{{task}} [[Category:Simple]]


;Task:
;Task:
Line 15: Line 15:


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>
<syntaxhighlight lang="0815">
}:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65:
}:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65:
x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s:
x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s:
</syntaxhighlight>
</lang>


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F is_even(i)
<syntaxhighlight lang="11l">F is_even(i)
R i % 2 == 0
R i % 2 == 0


F is_odd(i)
F is_odd(i)
R i % 2 == 1</lang>
R i % 2 == 1</syntaxhighlight>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
<lang 6502 assembly>
<syntaxhighlight lang="6502 assembly">
.lf evenodd6502.lst
.lf evenodd6502.lst
.cr 6502
.cr 6502
Line 77: Line 77:
;------------------------------------------------------
;------------------------------------------------------
.en
.en
</syntaxhighlight>
</lang>

=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==


===Non-Destructive===
===Non-Destructive===
<lang 68000devpac>BTST D0,#1
<syntaxhighlight lang="68000devpac">BTST D0,#1
BNE isOdd
BNE isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>


===Destructive===
===Destructive===


<lang 68000devpac>AND.B D0,#1
<syntaxhighlight lang="68000devpac">AND.B D0,#1
BNE isOdd
BNE isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>


<lang 68000devpac>ROR.B D0,#1
<syntaxhighlight lang="68000devpac">ROR.B D0,#1
BCS isOdd
BCS isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>


<lang 68000devpac>ROXR.B D0,#1
<syntaxhighlight lang="68000devpac">ROXR.B D0,#1
BCS isOdd
BCS isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>


<lang 68000devpac>LSR.B D0,#1
<syntaxhighlight lang="68000devpac">LSR.B D0,#1
BCS isOdd
BCS isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>


<lang 68000devpac>ASR.B D0,#1
<syntaxhighlight lang="68000devpac">ASR.B D0,#1
BCS isOdd
BCS isOdd
;else, is even.</lang>
;else, is even.</syntaxhighlight>




Line 114: Line 115:
The instruction that's doing all the work here is <code>rar</code>, which is a bitwise right rotate
The instruction that's doing all the work here is <code>rar</code>, which is a bitwise right rotate
of the accumulator through the carry flag. That leaves the low bit in the carry flag, which will be
of the accumulator through the carry flag. That leaves the low bit in the carry flag, which will be
set if odd and clear if even.
set if odd and clear if even.


<lang 8080asm>CMDLIN: equ 80h ; Location of CP/M command line argument
<syntaxhighlight lang="8080asm">CMDLIN: equ 80h ; Location of CP/M command line argument
puts: equ 9h ; Syscall to print a string
puts: equ 9h ; Syscall to print a string
;;; Check if number given on command line is even or odd
;;; Check if number given on command line is even or odd
org 100h
org 100h
lxi h,CMDLIN ; Find length of argument
lxi h,CMDLIN ; Find length of argument
mov a,m
mov a,m
add l ; Look up last character (digit)
add l ; Look up last character (digit)
mov l,a
mov l,a
Line 132: Line 133:
jmp 5 ; So print 'even'
jmp 5 ; So print 'even'
even: db 'Even$' ; Strings
even: db 'Even$' ; Strings
odd: db 'Odd$'</lang>
odd: db 'Odd$'</syntaxhighlight>


{{out}}
{{out}}
Line 148: Line 149:
=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
===Non-Destructive===
===Non-Destructive===
<lang asm>test ax,1
<syntaxhighlight lang="asm">test ax,1
jne isOdd
jne isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


===Destructive===
===Destructive===
<lang asm>and ax,1
<syntaxhighlight lang="asm">and ax,1
jne isOdd
jne isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


<lang asm>ror ax,1
<syntaxhighlight lang="asm">ror ax,1
jc isOdd
jc isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


<lang asm>rcr ax,1
<syntaxhighlight lang="asm">rcr ax,1
jc isOdd
jc isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


<lang asm>sar ax,1
<syntaxhighlight lang="asm">sar ax,1
jc isOdd
jc isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


<lang asm>shr ax,1
<syntaxhighlight lang="asm">shr ax,1
jc isOdd
jc isOdd
;else, is even</lang>
;else, is even</syntaxhighlight>


The <code>DIV</code> instruction can also work, but using <code>DIV</code> to divide by 2 is a waste of time, since the shift and rotate commands above do it faster.
The <code>DIV</code> instruction can also work, but using <code>DIV</code> to divide by 2 is a waste of time, since the shift and rotate commands above do it faster.
Line 177: Line 178:
=={{header|8th}}==
=={{header|8th}}==
The 'mod' method also works, but the bit method is fastest.
The 'mod' method also works, but the bit method is fastest.
<lang forth>: odd? \ n -- boolean
<syntaxhighlight lang="forth">: odd? \ n -- boolean
dup 1 n:band 1 n:= ;
dup 1 n:band 1 n:= ;
: even? \ n -- boolean
: even? \ n -- boolean
odd? not ;</lang>
odd? not ;</syntaxhighlight>


This could be shortened to:
This could be shortened to:
<lang forth>
<syntaxhighlight lang="forth">
: even? \ n -- f
: even? \ n -- f
1 n:band not ;
1 n:band not ;
: odd? \ n -- f
: odd? \ n -- f
even? not ;
even? not ;
</syntaxhighlight>
</lang>

=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B and android arm 64 bits*/
/* ARM assembly AARCH64 Raspberry PI 3B and android arm 64 bits*/
/* program oddEven64.s */
/* program oddEven64.s */


/*******************************************/
/*******************************************/
Line 208: Line 210:
sMessResultEven: .asciz " @ is even (pair) \n"
sMessResultEven: .asciz " @ is even (pair) \n"
szCarriageReturn: .asciz "\n"
szCarriageReturn: .asciz "\n"

/*********************************/
/*********************************/
/* UnInitialized data */
/* UnInitialized data */
Line 218: Line 220:
/*********************************/
/*********************************/
.text
.text
.global main
.global main
main: //entry of program
main: //entry of program


mov x0,#5
mov x0,#5
Line 227: Line 229:
mov x0,#2021
mov x0,#2021
bl testOddEven
bl testOddEven
100: //standard end of the program
100: //standard end of the program
mov x0, #0 //return code
mov x0, #0 //return code
mov x8, #EXIT //request to exit program
mov x8, #EXIT //request to exit program
svc #0 //perform the system call
svc #0 //perform the system call

qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResultOdd: .quad sMessResultOdd
qAdrsMessResultOdd: .quad sMessResultOdd
Line 266: Line 268:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 273: Line 275:
2021 is odd (impair)
2021 is odd (impair)
</pre>
</pre>

=={{header|ABAP}}==
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
cl_demo_output=>display(
cl_demo_output=>display(
VALUE string_table(
VALUE string_table(
Line 286: Line 289:
)
)
).
).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 305: Line 308:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC OddByAnd(INT v)
<syntaxhighlight lang="action!">PROC OddByAnd(INT v)
IF (v&1)=0 THEN
IF (v&1)=0 THEN
Print(" even")
Print(" even")
Line 339: Line 342:


FOR i=-4 TO 4
FOR i=-4 TO 4
DO
DO
PrintF("%I is",i)
PrintF("%I is",i)
OddByAnd(i)
OddByAnd(i)
Line 346: Line 349:
PutE()
PutE()
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Even_or_odd.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Even_or_odd.png Screenshot from Atari 8-bit computer]
Line 362: Line 365:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>-- Ada has bitwise operators in package Interfaces,
<syntaxhighlight lang="ada">-- Ada has bitwise operators in package Interfaces,
-- but they work with Interfaces.Unsigned_*** types only.
-- but they work with Interfaces.Unsigned_*** types only.
-- Use rem or mod for Integer types, and let the compiler
-- Use rem or mod for Integer types, and let the compiler
Line 376: Line 379:
Put_Line ("Something went really wrong!");
Put_Line ("Something went really wrong!");
end if;
end if;
end;</lang>
end;</syntaxhighlight>


=={{header|Agda}}==
=={{header|Agda}}==
<syntaxhighlight lang="agda">
<lang Agda>even : ℕ → Bool
module EvenOrOdd where

open import Data.Bool using (Bool; false; true)
open import Data.Nat using (ℕ; zero; suc)

even : ℕ → Bool
odd : ℕ → Bool
odd : ℕ → Bool


Line 386: Line 395:


odd zero = false
odd zero = false
odd (suc n) = even n</lang>
odd (suc n) = even n
</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>if (x & 1) {
<syntaxhighlight lang="aime">if (x & 1) {
# x is odd
# x is odd
} else {
} else {
# x is even
# x is even
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># Algol 68 has a standard operator: ODD which returns TRUE if its integer #
<syntaxhighlight lang="algol68"># Algol 68 has a standard operator: ODD which returns TRUE if its integer #
# operand is odd and FALSE if it is even #
# operand is odd and FALSE if it is even #
# E.g.: #
# E.g.: #
Line 405: Line 415:
read( ( n ) );
read( ( n ) );
print( ( whole( n, 0 ), " is ", IF ODD n THEN "odd" ELSE "even" FI, newline ) )
print( ( whole( n, 0 ), " is ", IF ODD n THEN "odd" ELSE "even" FI, newline ) )
</syntaxhighlight>
</lang>


=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
Because ALGOL-M lacks a built-in MOD operator or function and does not support bitwise operations on integers, the test is a bit cumbersome, but gets the job done.
Because ALGOL-M lacks a built-in MOD operator or function and does not support bitwise operations on integers, the test is a bit cumbersome, but gets the job done.
<lang algol>
<syntaxhighlight lang="algol">
BEGIN
BEGIN


Line 424: Line 434:
WRITE(K," IS ", IF EVEN(K) = 1 THEN "EVEN" ELSE "ODD");
WRITE(K," IS ", IF EVEN(K) = 1 THEN "EVEN" ELSE "ODD");


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 433: Line 443:


An alternate (but mathematically equivalent) coding, demonstrating the use of a conditional test as part of an assignment statement:
An alternate (but mathematically equivalent) coding, demonstrating the use of a conditional test as part of an assignment statement:
<lang algol>
<syntaxhighlight lang="algol">
% RETURN 1 IF EVEN, OTHERWISE 0 %
% RETURN 1 IF EVEN, OTHERWISE 0 %
INTEGER FUNCTION EVEN(I);
INTEGER FUNCTION EVEN(I);
Line 440: Line 450:
EVEN := (IF I = 2 * (I / 2) THEN 1 ELSE 0);
EVEN := (IF I = 2 * (I / 2) THEN 1 ELSE 0);
END;
END;
</syntaxhighlight>
</lang>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% the Algol W standard procedure odd returns true if its integer %
% the Algol W standard procedure odd returns true if its integer %
% parameter is odd, false if it is even %
% parameter is odd, false if it is even %
Line 450: Line 460:
write( i, " is ", if odd( i ) then "odd" else "even" )
write( i, " is ", if odd( i ) then "odd" else "even" )
end for_i
end for_i
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 460: Line 470:


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>odd: {x mod 2}
<syntaxhighlight lang="antlang">odd: {x mod 2}
even: {1 - x mod 2}</lang>
even: {1 - x mod 2}</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
The easiest way is probably to use modulo.
The easiest way is probably to use modulo.
<lang apl> 2|28
<syntaxhighlight lang="apl"> 2|28
0
0
2|37
2|37
1</lang>
1</syntaxhighlight>


So you can write a user-defined operator.
So you can write a user-defined operator.
Line 474: Line 484:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>set L to {3, 2, 1, 0, -1, -2, -3}
<syntaxhighlight lang="applescript">set L to {3, 2, 1, 0, -1, -2, -3}


set evens to {}
set evens to {}
Line 487: Line 497:
end repeat
end repeat


return {even:evens, odd:odds}</lang>
return {even:evens, odd:odds}</syntaxhighlight>
{{out}}
{{out}}
<lang AppleScript>{even:{2, 0, -2}, odd:{3, 1, -1, -3}}</lang>
<syntaxhighlight lang="applescript">{even:{2, 0, -2}, odd:{3, 1, -1, -3}}</syntaxhighlight>




Or, packaging reusable functions that can serve as arguments to '''filter''', '''partition''' etc
Or, packaging reusable functions that can serve as arguments to '''filter''', '''partition''' etc
(deriving '''even''' from mod, and '''odd''' from even):
(deriving '''even''' from mod, and '''odd''' from even):
<lang AppleScript>----------------------- EVEN OR ODD ------------------------
<syntaxhighlight lang="applescript">----------------------- EVEN OR ODD ------------------------


-- even :: Int -> Bool
-- even :: Int -> Bool
Line 552: Line 562:
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
if script is class of f then
f
f
Line 560: Line 570:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{{-5, -3, -1, 1, 3, 5}, {-6, -4, -2, 0, 2, 4, 6}}</lang>
<syntaxhighlight lang="applescript">{{-5, -3, -1, 1, 3, 5}, {-6, -4, -2, 0, 2, 4, 6}}</syntaxhighlight>


=={{header|Arendelle}}==
=={{header|Arendelle}}==
Line 574: Line 584:
"| @input | is odd!"
"| @input | is odd!"
}</pre>
}</pre>

=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI or android 32 bits */
/* ARM assembly Raspberry PI or android 32 bits */
/* program oddEven.s */
/* program oddEven.s */


/* REMARK 1 : this program use routines in a include file
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
see task Include a file language arm assembly
for the routine affichageMess conversion10
for the routine affichageMess conversion10
see at end of this program the instruction include */
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/* for constantes see task include a file in arm assembly */
Line 597: Line 608:
sMessResultEven: .asciz " @ is even (pair) \n"
sMessResultEven: .asciz " @ is even (pair) \n"
szCarriageReturn: .asciz "\n"
szCarriageReturn: .asciz "\n"

/*********************************/
/*********************************/
/* UnInitialized data */
/* UnInitialized data */
Line 607: Line 618:
/*********************************/
/*********************************/
.text
.text
.global main
.global main
main: @ entry of program
main: @ entry of program


mov r0,#5
mov r0,#5
Line 616: Line 627:
mov r0,#2021
mov r0,#2021
bl testOddEven
bl testOddEven
100: @ standard end of the program
100: @ standard end of the program
mov r0, #0 @ return code
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
svc #0 @ perform the system call

iAdrszCarriageReturn: .int szCarriageReturn
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResultOdd: .int sMessResultOdd
iAdrsMessResultOdd: .int sMessResultOdd
Line 630: Line 641:
// r0 contains à number
// r0 contains à number
testOddEven:
testOddEven:
push {r2-r8,lr} @ save registers
push {r2-r8,lr} @ save registers
tst r0,#1 @ test bit 0 to one
tst r0,#1 @ test bit 0 to one
beq 1f @ if result are all zéro, go to even
beq 1f @ if result are all zéro, go to even
Line 654: Line 665:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>


=={{header|ArnoldC}}==
=={{header|ArnoldC}}==
<lang arnoldc>LISTEN TO ME VERY CAREFULLY isOdd
<syntaxhighlight lang="arnoldc">LISTEN TO ME VERY CAREFULLY isOdd
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
GIVE THESE PEOPLE AIR
Line 688: Line 699:
DO IT NOW showParity 6
DO IT NOW showParity 6
DO IT NOW showParity -11
DO IT NOW showParity -11
YOU HAVE BEEN TERMINATED</lang>
YOU HAVE BEEN TERMINATED</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 702: Line 713:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>loop (neg 5)..5 [x][
<syntaxhighlight lang="rebol">loop (neg 5)..5 [x][
if? even? x -> print [pad to :string x 4 ": even"]
if? even? x -> print [pad to :string x 4 ": even"]
else -> print [pad to :string x 4 ": odd"]
else -> print [pad to :string x 4 ": odd"]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}

<pre> -5 : odd
<pre> -5 : odd
-4 : even
-4 : even
Line 723: Line 732:


=={{header|Asymptote}}==
=={{header|Asymptote}}==
<lang Asymptote>for (int i = 1; i <= 10; ++i) {
<syntaxhighlight lang="asymptote">for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
if (i % 2 == 0) {
write(string(i), " is even");
write(string(i), " is even");
Line 729: Line 738:
write(string(i), " is odd");
write(string(i), " is odd");
}
}
}</lang>
}</syntaxhighlight>




=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Bitwise ops are probably most efficient:
Bitwise ops are probably most efficient:
<lang AHK>if ( int & 1 ){
<syntaxhighlight lang="ahk">if ( int & 1 ){
; do odd stuff
; do odd stuff
}else{
}else{
; do even stuff
; do even stuff
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK>function isodd(x) {
<syntaxhighlight lang="awk">function isodd(x) {
return (x%2)!=0;
return x % 2 != 0
}
}


function iseven(x) {
function iseven(x) {
return (x%2)==0;
return x % 2 == 0
}</lang>
}</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<lang freebasic>' Even or odd
<syntaxhighlight 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</syntaxhighlight>
{{works with|Commodore BASIC|2.0}}

==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">' Even or odd
OPTION MEMTYPE int
OPTION MEMTYPE int
SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim
SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim
n = IIF$(dim < 2, 0, VAL(arg$[1]))
n = IIF$(dim < 2, 0, VAL(arg$[1]))
PRINT n, " is ", IIF$(EVEN(n), "even", "odd")</lang>
PRINT n, " is ", IIF$(EVEN(n), "even", "odd")</syntaxhighlight>

{{out}}
{{out}}
<pre>prompt$ ./even-or-odd 42
<pre>prompt$ ./even-or-odd 42
Line 762: Line 778:
41 is odd</pre>
41 is odd</pre>


=={{header|BASIC}}==
==={{header|BASIC256}}===
==={{header|Applesoft BASIC}}===
{{works with|True BASIC}}
<syntaxhighlight lang="basic256">for i = 1 to 10
if (i mod 2) then print i;" is odd" else print i;" is even"
next i
end</syntaxhighlight>


==={{header|BBC BASIC}}===
<lang basic>10 INPUT "ENTER A NUMBER: ";N
{{works with|BBC BASIC for Windows}}
20 IF N/2 <> INT(N/2) THEN PRINT "THE NUMBER IS ODD":GOTO 40
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.
30 PRINT "THE NUMBER IS EVEN"
<syntaxhighlight lang="bbcbasic"> IF FNisodd%(14) PRINT "14 is odd" ELSE PRINT "14 is even"
40 END</lang>
IF FNisodd%(15) PRINT "15 is odd" ELSE PRINT "15 is even"
{{works with|Commodore BASIC|2.0}}
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
==={{header|Commodore BASIC}}===
DEF FNisodd%(n%) = (n% AND 1) <> 0


REM Works for -2^53 <= n# <= 2^53
DEF FNisodd#(n#) = n# <> 2 * INT(n# / 2)</syntaxhighlight>
{{out}}
<pre>
14 is even
15 is odd
9876543210 is even
9876543211 is odd
</pre>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
Uses bitwise AND as suggested.
Uses bitwise AND as suggested.
<syntaxhighlight lang="qbasic">10 cls
20 for n = 1 to 10
30 print n;
40 if (n and 1) = 1 then print "is odd" else print "is even"
50 next n
60 end</syntaxhighlight>


==={{header|Commodore BASIC}}===
<lang gwbasic>10 rem determine if integer is even or odd
Uses bitwise AND as suggested.
<syntaxhighlight lang="gwbasic">10 rem determine if integer is even or odd
20 print "Enter an integer:";
20 print "Enter an integer:";
30 input i%
30 input i%
Line 781: Line 825:
40 eo$="even"
40 eo$="even"
50 if (i% and 1)=1 then eo$="odd"
50 if (i% and 1)=1 then eo$="odd"
60 print "The number ";i%;"is ";eo$;"."</lang>
60 print "The number ";i%;"is ";eo$;"."</syntaxhighlight>

==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64

Dim n As Integer

Do
Print "Enter an integer or 0 to finish : ";
Input "", n
If n = 0 Then
Exit Do
ElseIf n Mod 2 = 0 Then
Print "Your number is even"
Print
Else
Print "Your number is odd"
Print
End if
Loop

End</syntaxhighlight>

==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sAnswer, sMessage As String

sAnswer = InputBox("Input an integer", "Odd or even")

If IsInteger(sAnswer) Then
If Odd(Val(sAnswer)) Then sMessage = "' is an odd number"
If Even(Val(sAnswer)) Then sMessage = "' is an even number"
Else
sMessage = "' does not compute!!"
Endif

Print "'" & sAnswer & sMessage

End</syntaxhighlight>

Output:
<pre>
'25' is an odd number
'100' is an even number
'Fred' does not compute!!
</pre>


==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
<lang gwbasic>
<syntaxhighlight lang="gwbasic">
10 INPUT "Enter a number: ", N
10 INPUT "Enter a number: ", N
20 IF N MOD 2 = 1 THEN PRINT "It is odd." ELSE PRINT "It is even."</lang>
20 IF N MOD 2 = 1 THEN PRINT "It is odd." ELSE PRINT "It is even."</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 DEF ODD(X)=MOD(X,2)
<syntaxhighlight lang="is-basic">100 DEF ODD(X)=MOD(X,2)
110 INPUT PROMPT "Enter a number: ":X
110 INPUT PROMPT "Enter a number: ":X
120 IF ODD(X) THEN
120 IF ODD(X) THEN
Line 795: Line 884:
140 ELSE
140 ELSE
150 PRINT X;"is even."
150 PRINT X;"is even."
160 END IF</lang>
160 END IF</syntaxhighlight>

==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">n=12

if n mod 2 = 0 then print "even" else print "odd"</syntaxhighlight>


==={{header|Minimal BASIC}}===
==={{header|Minimal BASIC}}===
{{works with|IS-BASIC}}
<lang gwbasic>
10 REM Even or odd
<syntaxhighlight lang="gwbasic">10 REM Even or odd
20 PRINT "Enter an integer number";
20 PRINT "Enter an integer number";
30 INPUT N
30 INPUT N
40 IF N/2 <> INT(N/2) THEN 70
40 IF N/2 <> INT(N/2) THEN 70
Line 806: Line 901:
60 GOTO 80
60 GOTO 80
70 PRINT "The number is odd."
70 PRINT "The number is odd."
80 END
80 END</syntaxhighlight>

</lang>
==={{header|MSX Basic}}===
Uses bitwise AND as suggested.
<syntaxhighlight lang="qbasic">10 CLS
20 FOR N = -5 TO 5
30 PRINT N;
40 IF (N AND 1) = 1 THEN PRINT "is odd" ELSE PRINT "is even"
50 NEXT N
60 END</syntaxhighlight>

==={{header|PureBasic}}===
<syntaxhighlight 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</syntaxhighlight>


==={{header|QB64}}===
==={{header|QB64}}===
NB: Line numbers are not required in this language. Further, because of the Int variable type used for input, floating point values will not be accepted by the program. 0 is a problem, though, as it returns "Even" in the code below, even though it is not mathematically an even value. For code brevity, the 0 problem is not addressed. Finally, No Even or Odd predicates exist in this language.
NB: Line numbers are not required in this language. Further, because of the Int variable type used for input, floating point values will not be accepted by the program. 0 is a problem, though, as it returns "Even" in the code below, even though it is not mathematically an even value. For code brevity, the 0 problem is not addressed. Finally, No Even or Odd predicates exist in this language.
<lang QB64>'This is a comment line. It also could have been preceded with "Rem"
<syntaxhighlight lang="qb64">'This is a comment line. It also could have been preceded with "Rem"


Dim i% 'This line is not necessary, but % strict casts
Dim i% 'This line is not necessary, but % strict casts
'as an Int (2 bytes). "As Int" could have been used instead.
'as an Int (2 bytes). "As Int" could have been used instead.
Input "#? ", i% 'Prints "#? " as a prompt and waits
Input "#? ", i% 'Prints "#? " as a prompt and waits
'for user input terminated by pressing [ENTER].
'for user input terminated by pressing [ENTER].

'Binary integers example
'Binary integers example
If i% And 1 Then 'Test whether the input value AND 1 is 0 (false) or 1 (true).
If i% And 1 Then 'Test whether the input value AND 1 is 0 (false) or 1 (true).
'There is no global or constant "True" or "False".
'There is no global or constant "True" or "False".
Print "Odd" 'Prints "Odd" if the above tested "true".
Print "Odd" 'Prints "Odd" if the above tested "true".
Else 'This could have been also been "ElseIf Not (i% And 1)"
Else 'This could have been also been "ElseIf Not (i% And 1)"
Print "Even" 'Prints "Even in all other cases (Else)
Print "Even" 'Prints "Even in all other cases (Else)
'or if the logical inverse of the input value AND 1 tested
'or if the logical inverse of the input value AND 1 tested
'"true" (ElseIf).
'"true" (ElseIf).
Line 833: Line 945:
Else
Else
Print "Still Even"
Print "Still Even"
End If</lang>
End If</syntaxhighlight>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|Run BASIC}}
<syntaxhighlight lang="qbasic">FOR i = 1 TO 10
IF i AND 1 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
NEXT i</syntaxhighlight>

==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 CLS
20 FOR n = -5 TO 5
30 PRINT n;
40 IF n % 2 <> 0 THEN PRINT " is odd" ELSE PRINT " is even"
50 NEXT n
60 END</syntaxhighlight>

==={{header|Run BASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="runbasic">for i = 1 to 10
if i and 1 then print i;" is odd" else print i;" is even"
next i</syntaxhighlight>
<pre>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</pre>

==={{header|S-BASIC}}===
S-BASIC lacks a MOD operator but supports bitwise operations on integer variables, so that is the approach taken.
<syntaxhighlight lang="basic">
rem - return true (-1) if even, otherwise false (0)
function even(i = integer) = integer
var one = integer rem - both operands must be variables
one = 1
end = ((i and one) = 0)

rem - exercise the function
var i = integer
for i = 1 to 10 step 3
print i; " is ";
if even(i) then
print "even"
else
print "odd"
next

end</syntaxhighlight>
{{out}}
<pre> 1 is odd
4 is even
7 is odd
10 is even</pre>

==={{header|TI-83 BASIC}}===
TI-83 BASIC does not have a modulus operator.
<syntaxhighlight lang="ti83b">If fPart(.5Ans
Then
Disp "ODD
Else
Disp "EVEN
End</syntaxhighlight>


==={{header|Tiny BASIC}}===
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<lang>10 PRINT "Enter a number:"
<syntaxhighlight lang="basic">10 PRINT "Enter a number:"
20 INPUT N
20 INPUT N
30 IF 2*(N/2) = N THEN GOTO 60
30 IF 2*(N/2) = N THEN GOTO 60
40 PRINT "It's odd."
40 PRINT "It's odd."
50 END
50 END
60 PRINT "It's even."</lang>
60 PRINT "It's even."
70 END</syntaxhighlight>

==={{header|BASIC256}}===
{{works with|True BASIC}}
<lang BASIC256>for i = 1 to 10
if (i mod 2) then print i;" is odd" else print i;" is even"
next i
end</lang>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QRun BASIC}}
<lang qbasic>FOR i = 1 TO 10
IF i AND 1 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
NEXT i</lang>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{works with|BASIC256}}
{{works with|BASIC256}}
<lang qbasic>FOR i = 1 to 10
<syntaxhighlight lang="qbasic">FOR i = 1 to 10
IF MOD(i, 2) = 0 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
IF MOD(i, 2) = 0 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
NEXT i
NEXT i
END</lang>
END</syntaxhighlight>

==={{header|VBA}}===
<pre>4 ways = 4 Functions :
IsEven ==> Use the even and odd predicates
IsEven2 ==> Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even
IsEven3 ==> Divide i by 2. The remainder equals 0 if i is even.
IsEven4 ==> Use modular congruences</pre>

<syntaxhighlight lang="vb">Option Explicit

Sub Main_Even_Odd()
Dim i As Long

For i = -50 To 48 Step 7
Debug.Print i & " : IsEven ==> " & IIf(IsEven(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven2 ==> " & IIf(IsEven2(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven3 ==> " & IIf(IsEven3(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven4 ==> " & IIf(IsEven4(i), "is even", "is odd")
Next
End Sub

Function IsEven(Number As Long) As Boolean
'Use the even and odd predicates
IsEven = (WorksheetFunction.Even(Number) = Number)
End Function

Function IsEven2(Number As Long) As Boolean
'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.
Dim lngTemp As Long
lngTemp = CLng(Right(CStr(Number), 1))
If (lngTemp And 1) = 0 Then IsEven2 = True
End Function

Function IsEven3(Number As Long) As Boolean
'Divide i by 2.
'The remainder equals 0 if i is even.
Dim sngTemp As Single
sngTemp = Number / 2
IsEven3 = ((Int(sngTemp) - sngTemp) = 0)
End Function

Function IsEven4(Number As Long) As Boolean
'Use modular congruences
IsEven4 = (Number Mod 2 = 0)
End Function</syntaxhighlight>
{{out}}
<pre>-50 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-43 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-36 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-29 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-22 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-15 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-8 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-1 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
6 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
13 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
20 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
27 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
34 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
41 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
48 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even</pre>

==={{header|VBScript}}===
<syntaxhighlight lang="vb">Function odd_or_even(n)
If n Mod 2 = 0 Then
odd_or_even = "Even"
Else
odd_or_even = "Odd"
End If
End Function

WScript.StdOut.Write "Please enter a number: "
n = WScript.StdIn.ReadLine
WScript.StdOut.Write n & " is " & odd_or_even(CInt(n))
WScript.StdOut.WriteLine</syntaxhighlight>
{{Out}}
<pre>C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 6
6 is Even

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 9
9 is Odd

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: -1
-1 is Odd</pre>

==={{header|Visual Basic .NET}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Module Module1

Sub Main()
Dim str As String
Dim num As Integer
While True
Console.Write("Enter an integer or 0 to finish: ")
str = Console.ReadLine()
If Integer.TryParse(str, num) Then
If num = 0 Then
Exit While
End If
If num Mod 2 = 0 Then
Console.WriteLine("Even")
Else
Console.WriteLine("Odd")
End If
Else
Console.WriteLine("Bad input.")
End If
End While
End Sub

End Module</syntaxhighlight>
==== BigInteger ====
{{Libheader|System.Numerics}}
<syntaxhighlight lang="vbnet">Imports System.Numerics

Module Module1
Function IsOdd(bi As BigInteger) As Boolean
Return Not bi.IsEven
End Function

Function IsEven(bi As BigInteger) As Boolean
Return bi.IsEven
End Function

Sub Main()
' uncomment one of the following Dim statements
' Dim x As Byte = 3
' Dim x As Short = 3
' Dim x As Integer = 3
' Dim x As Long = 3
' Dim x As SByte = 3
' Dim x As UShort = 3
' Dim x As UInteger = 3
' Dim x As ULong = 3
' Dim x as BigInteger = 3
' the following three types give a warning, but will work
' Dim x As Single = 3
' Dim x As Double = 3
' Dim x As Decimal = 3

Console.WriteLine("{0} {1}", IsOdd(x), IsEven(x))
End Sub
End Module</syntaxhighlight>


==={{header|XBasic}}===
==={{header|XBasic}}===
{{works with|Windows XBasic}}
{{works with|Windows XBasic}}
<lang xbasic>PROGRAM "Even/Odd"
<syntaxhighlight lang="xbasic">PROGRAM "Even/Odd"


DECLARE FUNCTION Entry ()
DECLARE FUNCTION Entry ()
Line 877: Line 1,190:
END FUNCTION
END FUNCTION


END PROGRAM</lang>
END PROGRAM</syntaxhighlight>

==={{header|Yabasic}}===
{{trans|Phix}}
<syntaxhighlight lang="yabasic">for i = -5 to 5
print i, and(i,1), mod(i,2)
next
</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 FOR n=-3 TO 4: GO SUB 30: NEXT n
20 STOP
30 LET odd=FN m(n,2)
40 PRINT n;" is ";("Even" AND odd=0)+("Odd" AND odd=1)
50 RETURN
60 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off
<lang dos>
set /p i=Insert number:
@echo off
set /p i=Insert number:


::bitwise and
::bitwise and
Line 894: Line 1,221:


set test
set test
pause>nul
pause>nul</syntaxhighlight>
</lang>

=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
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>
{{out}}
<pre>
14 is even
15 is odd
9876543210 is even
9876543211 is odd
</pre>


=={{header|bc}}==
=={{header|bc}}==
There are no bitwise operations, so this solution compares a remainder with zero. Calculation of ''i % 2'' only works when ''scale = 0''.
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
<syntaxhighlight lang="bc">i = -3


/* Assumes that i is an integer. */
/* Assumes that i is an integer. */
Line 928: Line 1,232:
"
"
if (i % 2) "i is odd
if (i % 2) "i is odd
"</lang>
"</syntaxhighlight>


=={{header|Beads}}==
=={{header|Beads}}==
<lang beads>beads 1 program 'Even or odd'
<syntaxhighlight lang="beads">beads 1 program 'Even or odd'


calc main_init
calc main_init
loop across:[-10, -5, 10, 5] val:v
loop across:[-10, -5, 10, 5] val:v
log "{v}\todd:{is_odd(v)}\teven:{is_even(v)}"</lang>
log "{v}\todd:{is_odd(v)}\teven:{is_even(v)}"</syntaxhighlight>


{{out}}
{{out}}
Line 946: Line 1,250:


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang befunge>&2%52**"E"+,@</lang>
<syntaxhighlight lang="befunge">&2%52**"E"+,@</syntaxhighlight>


Outputs E if even, O if odd.
Outputs E if even, O if odd.

=={{header|Binary Lambda Calculus}}==
In lambda calculus, the oddness of a given church numeral n can be computed as n applications of <code>not</code> to <code>false</code>: <code>\n. n (\b\x\y. b y x) (\x\y.y)</code>, which in BLC is

<pre>00 01 01 10 0000000101111010110 000010</pre>

To compute the evenness, one need only replace <code>false</code> by <code>true</code>, i.e. replace the final 0 bit by 10.


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>
<syntaxhighlight lang="bqn">
odd ← 2⊸|
odd ← 2⊸|


!0 ≡ odd 12
!0 ≡ odd 12
!1 ≡ odd 31</lang>
!1 ≡ odd 31</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Not the simplest solution, but the cheapest if the number that must be tested has thousands of digits.
Not the simplest solution, but the cheapest if the number that must be tested has thousands of digits.
<lang bracmat>( ( even
<syntaxhighlight lang="bracmat">( ( even
=
=
. @( !arg
. @( !arg
Line 987: Line 1,298:
& eventest$857234098750432987502398457089435
& eventest$857234098750432987502398457089435
& oddtest$857234098750432987502398457089435
& oddtest$857234098750432987502398457089435
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>5556 is even
<pre>5556 is even
Line 995: Line 1,306:


=={{header|Brainf***}}==
=={{header|Brainf***}}==
Assumes that input characters are an ASCII representation of a valid integer.
Assumes that input characters are an ASCII representation of a valid integer.
Output is input <tt>mod</tt> 2.
Output is input <tt>mod</tt> 2.
<lang bf>,[>,----------] Read until newline
<syntaxhighlight lang="bf">,[>,----------] Read until newline
++< Get a 2 and move into position
++< Get a 2 and move into position
[->-[>+>>]> Do
[->-[>+>>]> Do
Line 1,004: Line 1,315:
>[-]<++++++++ Clear and get an 8
>[-]<++++++++ Clear and get an 8
[>++++++<-] to get a 48
[>++++++<-] to get a 48
>[>+<-]>. to get n % 2 to ASCII and print</lang>
>[>+<-]>. to get n % 2 to ASCII and print</syntaxhighlight>


If one need only determine rather than act on the parity of the input,
If one need only determine rather than act on the parity of the input,
the following is sufficient; it terminates either quickly or never.
the following is sufficient; it terminates either quickly or never.
<lang bf>,[>,----------]<[--]</lang>
<syntaxhighlight lang="bf">,[>,----------]<[--]</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>2.%</lang>
<syntaxhighlight lang="burlesque">2.%</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Test by bitwise and'ing 1, works for any builtin integer type as long as it's 2's complement (it's always so nowadays):
Test by bitwise and'ing 1, works for any builtin integer type as long as it's 2's complement (it's always so nowadays):
<lang c>if (x & 1) {
<syntaxhighlight lang="c">if (x & 1) {
/* x is odd */
/* x is odd */
} else {
} else {
/* or not */
/* or not */
}</lang>
}</syntaxhighlight>
If using long integer type from GMP (<code>mpz_t</code>), there are provided macros:
If using long integer type from GMP (<code>mpz_t</code>), there are provided macros:
<lang c>mpz_t x;
<syntaxhighlight lang="c">mpz_t x;
...
...
if (mpz_even_p(x)) { /* x is even */ }
if (mpz_even_p(x)) { /* x is even */ }
if (mpz_odd_p(x)) { /* x is odd */ }</lang>
if (mpz_odd_p(x)) { /* x is odd */ }</syntaxhighlight>
The macros evaluate <code>x</code> more than once, so it should not be something with side effects.
The macros evaluate <code>x</code> more than once, so it should not be something with side effects.


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>namespace RosettaCode
<syntaxhighlight lang="csharp">namespace RosettaCode
{
{
using System;
using System;
Line 1,093: Line 1,404:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Test using the modulo operator, or use the C example from above.
Test using the modulo operator, or use the C example from above.
<lang cpp>bool isOdd(int x)
<syntaxhighlight lang="cpp">bool isOdd(int x)
{
{
return x % 2;
return x % 2;
Line 1,105: Line 1,416:
{
{
return !(x % 2);
return !(x % 2);
}</lang>
}</syntaxhighlight>


A slightly more type-generic version, for C++11 and later. This should theoretically work for any type convertible to <code>int</code>:
A slightly more type-generic version, for C++11 and later. This should theoretically work for any type convertible to <code>int</code>:


<lang cpp>
<syntaxhighlight lang="cpp">
template < typename T >
template < typename T >
constexpr inline bool isEven( const T& v )
constexpr inline bool isEven( const T& v )
{
{
Line 1,116: Line 1,427:
}
}


template <>
template <>
constexpr inline bool isEven< int >( const int& v )
constexpr inline bool isEven< int >( const int& v )
{
{
Line 1,122: Line 1,433:
}
}


template < typename T >
template < typename T >
constexpr inline bool isOdd( const T& v )
constexpr inline bool isOdd( const T& v )
{
{
return !isEven(v);
return !isEven(v);
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
Standard predicates:
Standard predicates:
<lang clojure>(if (even? some-var) (do-even-stuff))
<syntaxhighlight lang="clojure">(if (even? some-var) (do-even-stuff))
(if (odd? some-var) (do-odd-stuff))</lang>
(if (odd? some-var) (do-odd-stuff))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IF FUNCTION REM(Num, 2) = 0
<syntaxhighlight lang="cobol"> IF FUNCTION REM(Num, 2) = 0
DISPLAY Num " is even."
DISPLAY Num " is even."
ELSE
ELSE
DISPLAY Num " is odd."
DISPLAY Num " is odd."
END-IF</lang>
END-IF</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>isEven = (x) -> !(x%2)</lang>
<syntaxhighlight lang="coffeescript">isEven = (x) -> !(x%2)</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<lang cfm>
<syntaxhighlight lang="cfm">
function f(numeric n) {
function f(numeric n) {
return n mod 2?"odd":"even"
return n mod 2?"odd":"even"
}
}
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Standard predicates:
Standard predicates:
<lang lisp>(if (evenp some-var) (do-even-stuff))
<syntaxhighlight lang="lisp">(if (evenp some-var) (do-even-stuff))
(if (oddp some-other-var) (do-odd-stuff))</lang>
(if (oddp some-other-var) (do-odd-stuff))</syntaxhighlight>
===Alternate solution===
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]


<lang lisp>
<syntaxhighlight lang="lisp">
;; Project : Even or odd
;; Project : Even or odd


Line 1,164: Line 1,475:
(cond ((evenp nr) "even")
(cond ((evenp nr) "even")
((oddp nr) "odd")))
((oddp nr) "odd")))
(dotimes (n 10)
(dotimes (n 10)
(if (< n 1) (terpri))
(if (< n 1) (terpri))
(if (< n 9) (format t "~a" " "))
(if (< n 9) (format t "~a" " "))
(write(+ n 1)) (format t "~a" ": ")
(write(+ n 1)) (format t "~a" ": ")
(format t "~a" (evenodd (+ n 1))) (terpri))
(format t "~a" (evenodd (+ n 1))) (terpri))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,186: Line 1,497:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE EvenOdd;
MODULE EvenOdd;
IMPORT StdLog,Args,Strings;
IMPORT StdLog,Args,Strings;
Line 1,214: Line 1,525:
WHILE i < p.argc DO
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
StdLog.String(p.args[i] + " is:> ");
IF ODD(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
IF ODD(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
StdLog.Ln;INC(i)
Line 1,221: Line 1,532:
WHILE i < p.argc DO
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
StdLog.String(p.args[i] + " is:> ");
IF BitwiseOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
IF BitwiseOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
StdLog.Ln;INC(i)
Line 1,228: Line 1,539:
WHILE i < p.argc DO
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
StdLog.String(p.args[i] + " is:> ");
IF Odd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
IF Odd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
StdLog.Ln;INC(i)
Line 1,235: Line 1,546:
WHILE i < p.argc DO
WHILE i < p.argc DO
Strings.StringToInt(p.args[i],x,done);
Strings.StringToInt(p.args[i],x,done);
StdLog.String(p.args[i] + " is:> ");
StdLog.String(p.args[i] + " is:> ");
IF CongruenceOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
IF CongruenceOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END;
StdLog.Ln;INC(i)
StdLog.Ln;INC(i)
END;
END;
END Do;
END Do;
</syntaxhighlight>
</lang>
Execute: ^Q EvenOdd.Do 10 11 0 57 34 -23 -42~<br/>
Execute: ^Q EvenOdd.Do 10 11 0 57 34 -23 -42~<br/>
{{out}}
{{out}}
Line 1,279: Line 1,590:


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>#Using bitwise shift
<syntaxhighlight lang="crystal">#Using bitwise shift
def isEven_bShift(n)
def isEven_bShift(n)
n == ((n >> 1) << 1)
n == ((n >> 1) << 1)
Line 1,309: Line 1,620:
puts isEven_bAnd(21)
puts isEven_bAnd(21)
puts isOdd_bAnd(21)
puts isOdd_bAnd(21)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>false
<pre>false
Line 1,320: Line 1,631:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.bigint;
import std.stdio, std.bigint;


foreach (immutable i; -5 .. 6)
foreach (immutable i; -5 .. 6)
writeln(i, " ", i & 1, " ", i % 2, " ", i.BigInt % 2);
writeln(i, " ", i & 1, " ", i % 2, " ", i.BigInt % 2);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>-5 1 -1 -1
<pre>-5 1 -1 -1
Line 1,338: Line 1,649:
4 0 0 0
4 0 0 0
5 1 1 1</pre>
5 1 1 1</pre>

=={{header|Dart}}==
<syntaxhighlight lang="dart">void main() {
for (var i = 1; i <= 10; i++) {
if (i % 2 != 0) {
print("$i is odd");
} else {
print("$i is even");
}
}
}</syntaxhighlight>

=={{header|dc}}==
This macro expects an integer on the stack, pops it, and pushes 1 if it is odd, or 0 if it is even (independently from the precision currently set).
<syntaxhighlight lang="dc">[K Sk 0 k 2 % Lk k]</syntaxhighlight>


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$! in DCL, for integers, the least significant bit determines the logical value, where 1 is true and 0 is false
<syntaxhighlight lang="dcl">$! in DCL, for integers, the least significant bit determines the logical value, where 1 is true and 0 is false
$
$
$ i = -5
$ i = -5
Line 1,347: Line 1,673:
$ if .not. i then $ write sys$output i, " is even"
$ if .not. i then $ write sys$output i, " is even"
$ i = i + 1
$ i = i + 1
$ if i .le. 6 then $ goto loop1</lang>
$ if i .le. 6 then $ goto loop1</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @even_odd
<pre>$ @even_odd
Line 1,364: Line 1,690:


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program EvenOdd;
program EvenOdd;


Line 1,394: Line 1,720:
Readln;
Readln;
end.
end.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,414: Line 1,740:
10 is even
10 is even
</pre>
</pre>
=={{header|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>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>even n:
<syntaxhighlight lang="dejavu">even n:
= 0 % n 2
= 0 % n 2


Line 1,433: Line 1,752:
!. odd 7
!. odd 7
!. even 7
!. even 7
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>false
<pre>false
Line 1,441: Line 1,760:


=={{header|Diego}}==
=={{header|Diego}}==
<lang diego>use_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();


funct(isEven)_arg(i)_ret()_calc(i%2)_equals(0);
funct(isEven)_arg(i)_ret()_calc(i%2)_equals(0);


reset_namespace[];</lang>
reset_namespace[];</syntaxhighlight>

=={{header|DWScript}}==
Predicate:
<syntaxhighlight lang="delphi">var isOdd := Odd(i);</syntaxhighlight>
Bitwise and:
<syntaxhighlight lang="delphi">var isOdd := (i and 1)<>0;</syntaxhighlight>
Modulo:
<syntaxhighlight lang="delphi">var isOdd := (i mod 2)=1;</syntaxhighlight>

=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
a = 13
if a mod 2 = 0
print a & " is even"
else
print a & " is odd"
.
</syntaxhighlight>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
This implementation uses the <code>C</code> (logical AND multiplier register with memory) order. It will cause the machine to print an <tt>E</tt> if the number stored at address <i>θ</i>+15 is even, or an <tt>O</tt> if it is odd. As an example, we shall test the number 37 (<code>P18D</code> in EDSAC encoding).
This implementation uses the <code>C</code> (logical AND multiplier register with memory) order. It will cause the machine to print an <tt>E</tt> if the number stored at address <i>θ</i>+15 is even, or an <tt>O</tt> if it is odd. As an example, we shall test the number 37 (<code>P18D</code> in EDSAC encoding).
<lang edsac>[ Even or odd
<syntaxhighlight lang="edsac">[ Even or odd
===========
===========


Line 1,481: Line 1,818:
[ 15 ] P18D [ number to test: 37 ]
[ 15 ] P18D [ number to test: 37 ]


EZPF [ branch to load point ]</lang>
EZPF [ branch to load point ]</syntaxhighlight>
{{out}}
{{out}}
<pre>O</pre>
<pre>O</pre>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang Eiffel>--bit testing
<syntaxhighlight lang="eiffel">--bit testing
if i.bit_and (1) = 0 then
if i.bit_and (1) = 0 then
-- i is even
-- i is even
Line 1,499: Line 1,836:
if i \\ 2 = 0 then
if i \\ 2 = 0 then
-- i is even
-- i is even
end</lang>
end</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
import Integer
import Integer

def even_or_odd(n) when is_even(n), do: "#{n} is even"
def even_or_odd(n) when is_even(n), do: "#{n} is even"
def even_or_odd(n) , do: "#{n} is odd"
def even_or_odd(n) , do: "#{n} is odd"
# In second "def", the guard clauses of "is_odd(n)" is unnecessary.
# In second "def", the guard clauses of "is_odd(n)" is unnecessary.

# Another definition way
# Another definition way
def even_or_odd2(n) do
def even_or_odd2(n) do
Line 1,515: Line 1,852:
end
end


Enum.each(-2..3, fn n -> IO.puts RC.even_or_odd(n) end)</lang>
Enum.each(-2..3, fn n -> IO.puts RC.even_or_odd(n) end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,527: Line 1,864:
</pre>
</pre>
Other ways to test even-ness:
Other ways to test even-ness:
<lang elixir>rem(n,2) == 0</lang>
<syntaxhighlight lang="elixir">rem(n,2) == 0</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(require 'cl-lib)
<syntaxhighlight lang="lisp">(require 'cl-lib)


(defun even-or-odd-p (n)
(defun even-or-odd-p (n)
Line 1,539: Line 1,876:


(message "%d is %s" 3 (even-or-oddp 3))
(message "%d is %s" 3 (even-or-oddp 3))
(message "%d is %s" 2 (even-or-oddp 2))</lang>
(message "%d is %s" 2 (even-or-oddp 2))</syntaxhighlight>


{{out}}
{{out}}
Line 1,545: Line 1,882:
3 is odd
3 is odd
2 is even
2 is even




=={{header|EMal}}==
<syntaxhighlight lang="emal">
List evenCheckers = fun[
logic by int i do return i % 2 == 0 end,
logic by int i do return i & 1 == 0 end]
List oddCheckers = fun[
logic by int i do return i % 2 != 0 end,
logic by int i do return i & 1 == 1 end]
writeLine("integer".padStart(10, " ") + "|is_even" + "|is_odd |")
writeLine("----------+-------+-------+")
for each int i in range(-5, 6).append(3141592653)
write((text!i).padStart(10, " ") + "| ")
for each fun isEven in evenCheckers
write(isEven(i) + " ")
end
write("| ")
for each fun isOdd in oddCheckers
write(isOdd(i) + " ")
end
writeLine("|")
end
writeLine("----------+-------+-------+")
</syntaxhighlight>
{{out}}
<pre>
integer|is_even|is_odd |
----------+-------+-------+
-5| ⊥ ⊥ | ⊤ ⊤ |
-4| ⊤ ⊤ | ⊥ ⊥ |
-3| ⊥ ⊥ | ⊤ ⊤ |
-2| ⊤ ⊤ | ⊥ ⊥ |
-1| ⊥ ⊥ | ⊤ ⊤ |
0| ⊤ ⊤ | ⊥ ⊥ |
1| ⊥ ⊥ | ⊤ ⊤ |
2| ⊤ ⊤ | ⊥ ⊥ |
3| ⊥ ⊥ | ⊤ ⊤ |
4| ⊤ ⊤ | ⊥ ⊥ |
5| ⊥ ⊥ | ⊤ ⊤ |
3141592653| ⊥ ⊥ | ⊤ ⊤ |
----------+-------+-------+
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
===Using Division by 2 Method===
===Using Division by 2 Method===
<lang erlang>%% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
-module(even_odd).
-module(even_odd).
-export([main/0]).
-export([main/0]).
Line 1,560: Line 1,942:
true ->
true ->
io:format("even\n")
io:format("even\n")
end.
end.
</syntaxhighlight>
</lang>
===Using the least-significant bit method===
===Using the least-significant bit method===
<lang erlang> %% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang"> %% Implemented by Arjun Sunel
-module(even_odd2).
-module(even_odd2).
-export([main/0]).
-export([main/0]).
Line 1,575: Line 1,957:
true ->
true ->
io:format("even\n")
io:format("even\n")
end.
end.
</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>PROGRAM ODD_EVEN
<syntaxhighlight lang="erre">PROGRAM ODD_EVEN


! works for -2^15 <= n% < 2^15
! works for -2^15 <= n% < 2^15
Line 1,598: Line 1,980:
IF ISODD#(9876543211) THEN PRINT("9876543211 is odd") ELSE PRINT("9876543211 is even") END IF
IF ISODD#(9876543211) THEN PRINT("9876543211 is odd") ELSE PRINT("9876543211 is even") END IF
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,609: Line 1,991:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
Using standard function
Using standard function
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/math.e
include std/math.e


Line 1,615: Line 1,997:
? {i, is_even(i)}
? {i, is_even(i)}
end for
end for
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,632: Line 2,014:
=={{header|Excel}}==
=={{header|Excel}}==
Use the MOD function
Use the MOD function
<syntaxhighlight lang="excel">
<lang Excel>
=MOD(33;2)
=MOD(33;2)
=MOD(18;2)
=MOD(18;2)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,644: Line 2,026:


Use the ISEVEN function, returns TRUE or FALSE
Use the ISEVEN function, returns TRUE or FALSE
<syntaxhighlight lang="excel">
<lang Excel>
=ISEVEN(33)
=ISEVEN(33)
=ISEVEN(18)
=ISEVEN(18)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,656: Line 2,038:


Use the ISODD function, returns TRUE or FALSE
Use the ISODD function, returns TRUE or FALSE
<syntaxhighlight lang="excel">
<lang Excel>
=ISODD(33)
=ISODD(33)
=ISODD(18)
=ISODD(18)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,670: Line 2,052:


Bitwise and:
Bitwise and:
<lang fsharp>let isEven x =
<syntaxhighlight lang="fsharp">let isEven x =
x &&& 1 = 0</lang>
x &&& 1 = 0</syntaxhighlight>


Modulo:
Modulo:
<lang fsharp>let isEven x =
<syntaxhighlight lang="fsharp">let isEven x =
x % 2 = 0</lang>
x % 2 = 0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Line 1,691: Line 2,073:
=={{header|Fish}}==
=={{header|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.
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
<syntaxhighlight lang="fish"><v"Please enter a number:"a
>l0)?!vo v < v o<
>l0)?!vo v < v o<
^ >i:a=?v>i:a=?v$a*+^>"The number is even."ar>l0=?!^>
^ >i:a=?v>i:a=?v$a*+^>"The number is even."ar>l0=?!^>
> >2%0=?^"The number is odd."ar ^</lang>
> >2%0=?^"The number is odd."ar ^</syntaxhighlight>
The actual computation is the 2%0= part. The rest is either user interface or parsing input.
The actual computation is the 2%0= part. The rest is either user interface or parsing input.


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang="forth">
<lang forth>: odd? ( n -- ? ) 1 and ;</lang>
: odd? ( n -- ? ) 1 and ;
: even? ( n -- ? ) odd? 0= ;

\ Every value not equal to zero is considered true. Only zero is considered false.
</syntaxhighlight>


=={{header|Fortran}}==
=={{header|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.
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.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 20:22:56
!Compilation started at Tue May 21 20:22:56
Line 1,782: Line 2,169:
write(6, '((13i3),a8/(13l3),a8/(13l3),a8)') j, 'n', odd(j), 'odd', even(j), 'even'
write(6, '((13i3),a8/(13l3),a8/(13l3),a8)') j, 'n', odd(j), 'odd', even(j), 'even'
end program oe
end program oe
</syntaxhighlight>
</lang>

=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64

Dim n As Integer

Do
Print "Enter an integer or 0 to finish : ";
Input "", n
If n = 0 Then
Exit Do
ElseIf n Mod 2 = 0 Then
Print "Your number is even"
Print
Else
Print "Your number is odd"
Print
End if
Loop

End</lang>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>isEven[x is isInteger] := getBit[x,0] == 0
<syntaxhighlight lang="frink">isEven[x is isInteger] := getBit[x,0] == 0
isOdd[x is isInteger] := getBit[x,0] == 1</lang>
isOdd[x is isInteger] := getBit[x,0] == 1</syntaxhighlight>


=={{header|Futhark}}==
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}


<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(x: int): bool = (x & 1) == 0
fun main(x: int): bool = (x & 1) == 0
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn OddOrEven( i as NSInteger ) as CFStringRef
CFStringRef result
if ( i mod 2 ) == 0 then result = @"Even" else result = @"Odd"
end fn = result

NSUInteger i

for i = 1 to 10
printf @"%d is %@", i, fn OddOrEven( i )
next

HandleEvents
</syntaxhighlight>



=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Even_or_odd}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.


'''Solutions'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.


'''Case 1.''' Intrinsic expressions:
In '''[https://formulae.org/?example=Even_or_odd this]''' page you can see the program(s) related to this task and their results.


[[File:Fōrmulæ - Even or odd 01.png]]
=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
Dim sAnswer, sMessage As String


[[File:Fōrmulæ - Even or odd 02.png]]
sAnswer = InputBox("Input an integer", "Odd or even")


'''Case 2.''' Using the Divides and DoesNotDivide expressions:
If IsInteger(sAnswer) Then
If Odd(Val(sAnswer)) Then sMessage = "' is an odd number"
If Even(Val(sAnswer)) Then sMessage = "' is an even number"
Else
sMessage = "' does not compute!!"
Endif


[[File:Fōrmulæ - Even or odd 03.png]]
Print "'" & sAnswer & sMessage


[[File:Fōrmulæ - Even or odd 04.png]]
End</lang>


'''Case 3.''' Using modular congruences
Output:

<pre>
[[File:Fōrmulæ - Even or odd 05.png]]
'25' is an odd number

'100' is an even number
[[File:Fōrmulæ - Even or odd 06.png]]
'Fred' does not compute!!

</pre>
'''Case 4.''' Using bitwise operations

[[File:Fōrmulæ - Even or odd 07.png]]

[[File:Fōrmulæ - Even or odd 08.png]]

'''Case 5.''' Using IsRational

[[File:Fōrmulæ - Even or odd 09.png]]

[[File:Fōrmulæ - Even or odd 10.png]]


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>IsEvenInt(n);
<syntaxhighlight lang="gap">IsEvenInt(n);
IsOddInt(n);</lang>
IsOddInt(n);</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
Using bitwise AND of the zero-bit.
Using bitwise AND of the zero-bit.
<lang genie>[indent = 4]
<syntaxhighlight lang="genie">[indent = 4]
/*
/*
Even or odd, in Genie
Even or odd, in Genie
Line 1,871: Line 2,259:
show_parity(2)
show_parity(2)
show_parity(-2)
show_parity(-2)
show_parity(-1)</lang>
show_parity(-1)</syntaxhighlight>


{{out}}
{{out}}
Line 1,883: Line 2,271:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,930: Line 2,318:
fmt.Println("odd")
fmt.Println("odd")
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,947: Line 2,335:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def isOdd = { int i -> (i & 1) as boolean }
<syntaxhighlight lang="groovy">def isOdd = { int i -> (i & 1) as boolean }
def isEven = {int i -> ! isOdd(i) }</lang>
def isEven = {int i -> ! isOdd(i) }</syntaxhighlight>
Test:
Test:
<lang groovy>1.step(20, 2) { assert isOdd(it) }
<syntaxhighlight lang="groovy">1.step(20, 2) { assert isOdd(it) }


50.step(-50, -2) { assert isEven(it) }</lang>
50.step(-50, -2) { assert isEven(it) }</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<code>even</code> and <code>odd</code> functions are already included in the standard Prelude.
<code>even</code> and <code>odd</code> functions are already included in the standard Prelude.
<lang haskell>Prelude> even 5
<syntaxhighlight lang="haskell">Prelude> even 5
False
False
Prelude> even 42
Prelude> even 42
Line 1,963: Line 2,351:
True
True
Prelude> odd 42
Prelude> odd 42
False</lang>
False</syntaxhighlight>


Where '''even''' is derived from '''rem''', and '''odd''' is derived from even:
Where '''even''' is derived from '''rem''', and '''odd''' is derived from even:
<lang haskell>import Prelude hiding (even, odd)
<syntaxhighlight lang="haskell">import Prelude hiding (even, odd)


even, odd
even, odd
Line 1,976: Line 2,364:


main :: IO ()
main :: IO ()
main = print (even <$> [0 .. 9])</lang>
main = print (even <$> [0 .. 9])</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[True,False,True,False,True,False,True,False,True,False]</pre>
<pre>[True,False,True,False,True,False,True,False,True,False]</pre>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang Hoon>|= n=@ud
<syntaxhighlight lang="hoon">|= n=@ud
?: =((mod n 2) 0)
?: =((mod n 2) 0)
"even"
"even"
"odd"</lang>
"odd"</syntaxhighlight>


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

=={{header|Insitux}}==
Exactly the same as [[Even_or_odd#Clojure|Clojure]], these are built-in predicates.
<syntaxhighlight lang="insitux">(if (even? some-var) (do-even-stuff))
(if (odd? some-var) (do-odd-stuff))</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Modulo:
Modulo:
<lang j> 2 | 2 3 5 7
<syntaxhighlight lang="j"> 2 | 2 3 5 7
0 1 1 1
0 1 1 1
2|2 3 5 7 + (2^89x)-1
2|2 3 5 7 + (2^89x)-1
1 0 0 0</lang>
1 0 0 0</syntaxhighlight>
Remainder:
Remainder:
<lang j> (= <.&.-:) 2 3 5 7
<syntaxhighlight lang="j"> (= <.&.-:) 2 3 5 7
1 0 0 0
1 0 0 0
(= <.&.-:) 2 3 5 7+(2^89x)-1
(= <.&.-:) 2 3 5 7+(2^89x)-1
0 1 1 1</lang>
0 1 1 1</syntaxhighlight>
Last bit in bit representation:
Last bit in bit representation:
<lang j> {:"1@#: 2 3 5 7
<syntaxhighlight lang="j"> {:"1@#: 2 3 5 7
0 1 1 1
0 1 1 1
{:"1@#: 2 3 5 7+(2^89x)-1
{:"1@#: 2 3 5 7+(2^89x)-1
1 0 0 0</lang>
1 0 0 0</syntaxhighlight>
Bitwise and:
Bitwise and:
<lang j> 1 (17 b.) 2 3 5 7
<syntaxhighlight lang="j"> 1 (17 b.) 2 3 5 7
0 1 1 1</lang>
0 1 1 1</syntaxhighlight>
Note: as a general rule, the simplest expressions in J should be preferred over more complex approaches.
Note: as a general rule, the simplest expressions in J should be preferred over more complex approaches.

=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn is_even<T>(anon n: T) -> bool => 0 == (n & 1)

fn is_odd<T>(anon n: T) -> bool => 0 != (n & 1)

fn main() {
for i in 0..11 {
println("{} {} {}", i, is_even(i), is_odd(i))
}
}
</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Bitwise and:
Bitwise and:
<lang java>public static boolean isEven(int i){
<syntaxhighlight lang="java">public static boolean isEven(int i){
return (i & 1) == 0;
return (i & 1) == 0;
}</lang>
}</syntaxhighlight>
Modulo:
Modulo:
<lang java>public static boolean isEven(int i){
<syntaxhighlight lang="java">public static boolean isEven(int i){
return (i % 2) == 0;
return (i % 2) == 0;
}</lang>
}</syntaxhighlight>
Arbitrary precision bitwise:
Arbitrary precision bitwise:
<lang java>public static boolean isEven(BigInteger i){
<syntaxhighlight lang="java">public static boolean isEven(BigInteger i){
return i.and(BigInteger.ONE).equals(BigInteger.ZERO);
return i.and(BigInteger.ONE).equals(BigInteger.ZERO);
}</lang>
}</syntaxhighlight>
Arbitrary precision bit test (even works for negative numbers because of the way <code>BigInteger</code> represents the bits of numbers):
Arbitrary precision bit test (even works for negative numbers because of the way <code>BigInteger</code> represents the bits of numbers):
<lang java>public static boolean isEven(BigInteger i){
<syntaxhighlight lang="java">public static boolean isEven(BigInteger i){
return !i.testBit(0);
return !i.testBit(0);
}</lang>
}</syntaxhighlight>
Arbitrary precision modulo:
Arbitrary precision modulo:
<lang java>public static boolean isEven(BigInteger i){
<syntaxhighlight lang="java">public static boolean isEven(BigInteger i){
return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);
return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
Bitwise:
Bitwise:
<lang javascript>function isEven( i ) {
<syntaxhighlight lang="javascript">function isEven( i ) {
return (i & 1) === 0;
return (i & 1) === 0;
}
}
</syntaxhighlight>
</lang>
Modulo:
Modulo:
<lang javascript>function isEven( i ) {
<syntaxhighlight lang="javascript">function isEven( i ) {
return i % 2 === 0;
return i % 2 === 0;
}
}
Line 2,050: Line 2,456:
function isEven( i ) {
function isEven( i ) {
return !(i % 2);
return !(i % 2);
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===
Lambda:
Lambda:
<lang javascript>// EMCAScript 6
<syntaxhighlight lang="javascript">// EMCAScript 6
const isEven = x => !(x % 2)</lang>
const isEven = x => !(x % 2)</syntaxhighlight>


or, avoiding type coercion:
or, avoiding type coercion:
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,082: Line 2,488:


return show([xs.filter(even), xs.filter(odd)]);
return show([xs.filter(even), xs.filter(odd)]);
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<pre>[[-6,-4,-2,0,2,4,6],[-5,-3,-1,1,3,5]]</pre>
<pre>[[-6,-4,-2,0,2,4,6],[-5,-3,-1,1,3,5]]</pre>


=={{header|jq}}==
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE
even == 2 rem null;
odd == even not.</syntaxhighlight>


=={{header|jq}}==
In practice, to test whether an integer, i, is even or odd in jq, one would typically use: i % 2
In practice, to test whether an integer, i, is even or odd in jq, one would typically use: i % 2


For example, if it were necessary to have a strictly boolean function that would test if its input is an even integer, one could define:
For example, if it were necessary to have a strictly boolean function that would test if its input is an even integer, one could define:
<lang jq>def is_even: type == "number" and floor == 0 and . % 2 == 0;</lang>
<syntaxhighlight lang="jq">def is_even: type == "number" and floor == 0 and . % 2 == 0;</syntaxhighlight>


The check that the floor is 0 is necessary as % is defined on floating point numbers.
The check that the floor is 0 is necessary as % is defined on floating point numbers.
Line 2,098: Line 2,508:
"is_odd" could be similarly defined:
"is_odd" could be similarly defined:


<lang jq>def is_odd: type == "number" and floor == 0 and . % 2 == 1;</lang>
<syntaxhighlight lang="jq">def is_odd: type == "number" and floor == 0 and . % 2 == 1;</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
Using bitwise and of low bit.
Using bitwise and of low bit.


<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* Even or Odd, in Jsish */
/* Even or Odd, in Jsish */
function isEven(n:number):boolean { return (n & 1) === 0; }
function isEven(n:number):boolean { return (n & 1) === 0; }
Line 2,123: Line 2,533:
isEven(-13) ==> false
isEven(-13) ==> false
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>
{{out}}
{{out}}
<pre>$ jsish --U isEven.jsi
<pre>$ jsish --U isEven.jsi
Line 2,133: Line 2,543:
=={{header|Julia}}==
=={{header|Julia}}==
Built-in functions:
Built-in functions:
<lang julia>iseven(i), isodd(i)</lang>
<syntaxhighlight lang="julia">iseven(i), isodd(i)</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
The following implementation uses the modulo of
The following implementation uses the modulo of
division by 2
division by 2
<syntaxhighlight lang="k">
<lang K>
oddp: {:[x!2;1;0]} /Returns 1 if arg. is odd
oddp: {:[x!2;1;0]} /Returns 1 if arg. is odd
evenp: {~oddp[x]} /Returns 1 if arg. is even
evenp: {~oddp[x]} /Returns 1 if arg. is even
Line 2,147: Line 2,557:
evenp 32
evenp 32
1
1
</syntaxhighlight>
</lang>




=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>( -5 5 ) [
<syntaxhighlight lang="klingphix">( -5 5 ) [
dup print " " print 2 mod ( ["Odd"] ["Even"] ) if print nl
dup print " " print 2 mod ( ["Odd"] ["Even"] ) if print nl
] for
] for


" " input</lang>
" " input</syntaxhighlight>
{{out}}
{{out}}
<pre>-5 Odd
<pre>-5 Odd
Line 2,170: Line 2,580:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 2,182: Line 2,592:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==


<lang scheme>
<syntaxhighlight lang="scheme">
{def is_odd {lambda {:i} {= {% :i 2} 1}}}
{def is_odd {lambda {:i} {= {% :i 2} 1}}}
-> is_odd
-> is_odd


Line 2,198: Line 2,608:
{is_even 2}
{is_even 2}
-> true
-> true
</syntaxhighlight>
</lang>


=={{header|L++}}==
=={{header|L++}}==
<lang lisp>(defn bool isEven (int x) (return (% x 2)))</lang>
<syntaxhighlight lang="lisp">(defn bool isEven (int x) (return (% x 2)))</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Line 2,208: Line 2,618:


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: even? 2 % not ;
<syntaxhighlight lang="lang5">: even? 2 % not ;
: odd? 2 % ;
: odd? 2 % ;
1 even? . # 0
1 even? . # 0
1 odd? . # 1</lang>
1 odd? . # 1</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define isoddoreven(i::integer) => {
<syntaxhighlight lang="lasso">define isoddoreven(i::integer) => {
#i % 2 ? return 'odd'
#i % 2 ? return 'odd'
return 'even'
return 'even'
}
}
isoddoreven(12)</lang>
isoddoreven(12)</syntaxhighlight>


=={{header|LC3 Assembly}}==
=={{header|LC3 Assembly}}==
Prints <tt>EVEN</tt> if the number stored in <tt>NUM</tt> is even, otherwise <tt>ODD</tt>.
Prints <tt>EVEN</tt> if the number stored in <tt>NUM</tt> is even, otherwise <tt>ODD</tt>.
<lang lc3asm> .ORIG 0x3000
<syntaxhighlight lang="lc3asm"> .ORIG 0x3000


LD R0,NUM
LD R0,NUM
Line 2,242: Line 2,652:
ODD .STRINGZ "ODD\n"
ODD .STRINGZ "ODD\n"


.END</lang>
.END</syntaxhighlight>

=={{header|Liberty BASIC}}==
<lang lb>n=12

if n mod 2 = 0 then print "even" else print "odd"</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">on even (n)

<lang lingo>on even (n)
return n mod 2 = 0
return n mod 2 = 0
end
end
Line 2,257: Line 2,661:
on odd (n)
on odd (n)
return n mode 2 <> 0
return n mode 2 <> 0
end</lang>
end</syntaxhighlight>


=={{header|Little Man Computer}}==
=={{header|Little Man Computer}}==
Line 2,263: Line 2,667:


LMC has no division instruction. To divide by 2 we could use repeated subtraction:
LMC has no division instruction. To divide by 2 we could use repeated subtraction:
<syntaxhighlight lang="little man computer">
<lang Little Man Computer>
// Input number; output its residue mod 2
// Input number; output its residue mod 2
INP // read input into acc
INP // read input into acc
Line 2,277: Line 2,681:
k2 DAT 2 // constant 2
k2 DAT 2 // constant 2
// end
// end
</syntaxhighlight>
</lang>
The above program might need 500 subtractions before it found the result. To speed things up we could use something along the following lines.
The above program might need 500 subtractions before it found the result. To speed things up we could use something along the following lines.
<syntaxhighlight lang="little man computer">
<lang Little Man Computer>
// Input number; output its residue mod 2
// Input number; output its residue mod 2
INP // read input into accumulator
INP // read input into accumulator
Line 2,301: Line 2,705:
save_acc DAT
save_acc DAT
// end
// end
</syntaxhighlight>
</lang>
Note: LMC, in its original form, does not support negative numbers. If the accumulator contains a number X, and a number Y > X is subtracted, then the negative flag is set and the value in the accumulator becomes undefined. So we can't assume that adding Y back to the accumulator will restore the value of X. If we want to use X again, we need to save it in RAM before doing the subtraction.
Note: LMC, in its original form, does not support negative numbers. If the accumulator contains a number X, and a number Y > X is subtracted, then the negative flag is set and the value in the accumulator becomes undefined. So we can't assume that adding Y back to the accumulator will restore the value of X. If we want to use X again, we need to save it in RAM before doing the subtraction.




=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>function odd n
<syntaxhighlight lang="livecode">function odd n
return (n bitand 1) = 1
return (n bitand 1) = 1
end odd
end odd
Line 2,312: Line 2,716:
function notEven n
function notEven n
return (n mod 2) = 1
return (n mod 2) = 1
end notEven</lang>
end notEven</syntaxhighlight>


=={{header|LLVM}}==
=={{header|LLVM}}==
<lang llvm>; This is not strictly LLVM, as it uses the C library function "printf".
<syntaxhighlight lang="llvm">; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; to just load the string into memory, and that would be boring.
Line 2,367: Line 2,771:
}
}


attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</lang>
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</syntaxhighlight>
{{out}}
{{out}}
<pre>0 is even
<pre>0 is even
Line 2,375: Line 2,779:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to even? :num
<syntaxhighlight lang="logo">to even? :num
output equal? 0 modulo :num 2
output equal? 0 modulo :num 2
end</lang>
end</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(even_odd).
:- object(even_odd).


Line 2,398: Line 2,802:


:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang text>
<syntaxhighlight lang="text">
| ?- even_odd::test_mod(1).
| ?- even_odd::test_mod(1).
odd
odd
Line 2,416: Line 2,820:
even
even
yes
yes
</syntaxhighlight>
</lang>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
<lang LOLCODE>HAI 1.4
<syntaxhighlight lang="lolcode">HAI 1.4
I HAS A integer
I HAS A integer
GIMMEH integer
GIMMEH integer
Line 2,430: Line 2,834:
VISIBLE "The integer is even."
VISIBLE "The integer is even."
OIC
OIC
KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>-- test for even number
<syntaxhighlight lang="lua">-- test for even number
if n % 2 == 0 then
if n % 2 == 0 then
print "The number is even"
print "The number is even"
Line 2,442: Line 2,846:
if not (n % 2 == 0) then
if not (n % 2 == 0) then
print "The number is odd"
print "The number is odd"
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Binary.Add take any numeric type, but value must be in range of 0 to 0xFFFFFFFF
Binary.Add take any numeric type, but value from newer versions can trait as unsigned with range of 0 to 0xFFFFFFFF (so if the number is out of this range, a cut made).

Print binary.and(0xFFFFFFF+10, 0XF)=9 // 0xFFFFFFFF is type Currency and return 4294967295, number 10 is type double so the final number for addition is type double.

Print binary.and(0xFFFFFFF&+10, 0XF)=9 // 0xFFFFFFFF& is type long and return -1, number 10 is type double so the final number for addition is type double.

Print binary.and(0x7FFFFFFF&*16&+10&, 0xF)=15 // 0x7FFFFFFF&*16& cant fit in long so it is type of double 34359738352 (this performed automatic). But if we give this Long A=0x7FFFFFFF&*16& we get an overflow error, because A is a Long, and 34359738352 can't fit.

So Mod if a perfect choice, using it with Decimals (character @ indicate a Decimal type or literal).
So Mod if a perfect choice, using it with Decimals (character @ indicate a Decimal type or literal).
Variable a take the type of input. There is no reason here to write it as def Odd(a as decimal)= binary.and(Abs(a), 1)=1
Variable a take the type of input. There is no reason here to write it as def Odd(a as decimal)= binary.and(Abs(a), 1)=1


Def used to define variables (an error occur if same variable exist), or to define one line local functions. If a function exist then replace code. This is the same for modules/functions, a newer definition alter an old definition with same name, in current module if they are local, or global if they defined as global, like this Function Global F(x) { code block here}.
Def used to define variables (an error occur if same variable exist), or to define one line local functions. If a function exist then replace code. This is the same for modules/functions, a newer definition alter an old definition with same name, in current module if they are local, or global if they defined as global, like this:

Function Global F(x) { code block here}.


A function F(x) {} is same as
A function F(x) {} is same as

<pre >
<pre >
Function F {
Function F {
Line 2,458: Line 2,872:
}
}
</pre >
</pre >

The same hold for Def Odd(a)=binary.and(Abs(a), 1)=1
The same hold for Def Odd(a)=binary.and(Abs(a), 1)=1
Interpreter execute this:
Interpreter execute this:
Line 2,470: Line 2,884:
So here is the task. Show an overflow from a decimal, then change function.
So here is the task. Show an overflow from a decimal, then change function.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckOdd {
Module CheckOdd {
Def Odd(a)= binary.and(Abs(a), 1)=1
Def Odd(a)= binary.and(Abs(a), 1)=1
Print Odd(-5), Odd(6), Odd(11)
Print Odd(-5), Odd(6), Odd(11)
Print Odd(21212121212122122122121@)
Try {
Print Odd(21212121212122122122121@)
}
Print Error$ ' overflow
def Odd(a)= Int(Abs(a)) mod 2 =1
def Odd(a)= Int(Abs(a)) mod 2 =1
Print Odd(21212121212122122122121@)
Print Odd(21212121212122122122121@)
Line 2,484: Line 2,894:
}
}
CheckOdd
CheckOdd
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`even', `ifelse(eval(`$1'%2),0,True,False)')
<syntaxhighlight lang="m4">define(`even', `ifelse(eval(`$1'%2),0,True,False)')
define(`odd', `ifelse(eval(`$1'%2),0,False,True)')
define(`odd', `ifelse(eval(`$1'%2),0,False,True)')


Line 2,494: Line 2,904:


odd(5)
odd(5)
odd(0)</lang>
odd(0)</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>EvenOrOdd := proc( x::integer )
<syntaxhighlight lang="maple">EvenOrOdd := proc( x::integer )
if x mod 2 = 0 then
if x mod 2 = 0 then
print("Even"):
print("Even"):
Line 2,504: Line 2,914:
end if:
end if:
end proc:
end proc:
EvenOrOdd(9);</lang>
EvenOrOdd(9);</syntaxhighlight>
<pre>"Odd"</pre>
<pre>"Odd"</pre>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>EvenQ[8]</lang>
<syntaxhighlight lang="mathematica">EvenQ[8]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
Bitwise And:
Bitwise And:
<lang Matlab> isOdd = logical(bitand(N,1));
<syntaxhighlight lang="matlab"> isOdd = logical(bitand(N,1));
isEven = ~logical(bitand(N,1)); </lang>
isEven = ~logical(bitand(N,1)); </syntaxhighlight>
Remainder of division by two
Remainder of division by two:
<lang Matlab> isOdd = logical(rem(N,2));
<syntaxhighlight lang="matlab"> isOdd = logical(rem(N,2));
isEven = ~logical(rem(N,2)); </lang>
isEven = ~logical(rem(N,2)); </syntaxhighlight>
Modulo: 2
Modulo: 2
<lang Matlab> isOdd = logical(mod(N,2));
<syntaxhighlight lang="matlab"> isOdd = logical(mod(N,2));
isEven = ~logical(mod(N,2)); </lang>
isEven = ~logical(mod(N,2)); </syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>evenp(n);
<syntaxhighlight lang="maxima">evenp(n);
oddp(n);</lang>
oddp(n);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>-- MAXScript : Even or Odd : N.H. 2019
<syntaxhighlight lang="maxscript">-- MAXScript : Even or Odd : N.H. 2019
-- Open the MAXScript Listener for input and output
-- Open the MAXScript Listener for input and output
userInt = getKBValue prompt:"Enter an integer and i will tell you if its Even or Odd : "
userInt = getKBValue prompt:"Enter an integer and i will tell you if its Even or Odd : "
Line 2,532: Line 2,942:
else if (Mod userInt 2) == 0 Then Print "Your number is even"
else if (Mod userInt 2) == 0 Then Print "Your number is even"
else Print "Your number is odd"
else Print "Your number is odd"
</syntaxhighlight>
</lang>


=={{header|Mercury}}==
=={{header|Mercury}}==
Mercury's 'int' module provides tests for even/odd, along with all the operators that would be otherwise used to implement them.
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.
<syntaxhighlight lang="mercury">even(N) % in a body, suceeeds iff N is even.
odd(N). % in a body, succeeds iff N is odd.
odd(N). % in a body, succeeds iff N is odd.


Line 2,545: Line 2,955:
even(N) :- N mod 2 = 0. % using division that truncates towards -infinity
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 rem 2 = 0. % using division that truncates towards zero
even(N) :- N /\ 1 = 0. % using bit-wise and.</lang>
even(N) :- N /\ 1 = 0. % using bit-wise and.</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>3 even?
<syntaxhighlight lang="min">3 even?
4 even?
4 even?
5 odd?
5 odd?
get-stack print</lang>
get-stack print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,559: Line 2,969:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>for i in range(-4, 4)
<syntaxhighlight lang="miniscript">for i in range(-4, 4)
if i % 2 == 0 then print i + " is even" else print i + " is odd"
if i % 2 == 0 then print i + " is even" else print i + " is odd"
end for</lang>
end for</syntaxhighlight>
{{out}}
{{out}}
<pre>-4 is even
<pre>-4 is even
Line 2,575: Line 2,985:
=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==
This uses bitwise AND
This uses bitwise AND
<lang mips>
<syntaxhighlight lang="mips">
.data
.data
even_str: .asciiz "Even"
even_str: .asciiz "Even"
Line 2,584: Line 2,994:
li $v0,5
li $v0,5
syscall
syscall

#perform bitwise AND and store in $a0
#perform bitwise AND and store in $a0
and $a0,$v0,1
and $a0,$v0,1

#set syscall to print dytomh
#set syscall to print dytomh
li $v0,4
li $v0,4

#jump to odd if the result of the AND operation
#jump to odd if the result of the AND operation
beq $a0,1,odd
beq $a0,1,odd
even:
even:
#load even_str message, and print
#load even_str message, and print
la $a0,even_str
la $a0,even_str
syscall
syscall

#exit program
#exit program
li $v0,10
li $v0,10
syscall
syscall

odd:
odd:
#load odd_str message, and print
#load odd_str message, and print
la $a0,odd_str
la $a0,odd_str
syscall
syscall

#exit program
#exit program
li $v0,10
li $v0,10
syscall
syscall
</syntaxhighlight>
</lang>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>/ 2 {x} ЗН</lang>
<syntaxhighlight lang="text">/ 2 {x} ЗН</syntaxhighlight>


''Result:'' "0" - number is even; "1" - number is odd.
''Result:'' "0" - number is even; "1" - number is odd.


=={{header|ML}}==
=={{header|ML}}==
<syntaxhighlight lang="ml">
<lang ml>
fun even( x: int ) = (x mod 2 = 0);
fun even( x: int ) = (x mod 2 = 0);
fun odd( x: int ) = (x mod 2 = 1);
fun odd( x: int ) = (x mod 2 = 1);
</syntaxhighlight>
</lang>
==={{header|mLite}}===
==={{header|mLite}}===
<lang ocaml>fun odd
<syntaxhighlight lang="ocaml">fun odd
(x rem 2 = 1) = true
(x rem 2 = 1) = true
| _ = false
| _ = false
;
;


fun even
fun even
(x rem 2 = 0) = true
(x rem 2 = 0) = true
| _ = false
| _ = false
;
;


</syntaxhighlight>
</lang>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE EvenOrOdd;
<syntaxhighlight lang="modula2">MODULE EvenOrOdd;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
FROM Terminal IMPORT WriteString,ReadChar;
Line 2,650: Line 3,060:


ReadChar
ReadChar
END EvenOrOdd.</lang>
END EvenOrOdd.</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>def isEven(n)
<syntaxhighlight lang="nanoquery">def isEven(n)
if ((n % 2) = 1)
if ((n % 2) = 1)
return false
return false
Line 2,668: Line 3,078:
println " is odd."
println " is odd."
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>1 is odd.
<pre>1 is odd.
Line 2,682: Line 3,092:


=={{header|Neko}}==
=={{header|Neko}}==
<lang neko>var number = 6;
<syntaxhighlight lang="neko">var number = 6;


if(number % 2 == 0) {
if(number % 2 == 0) {
Line 2,688: Line 3,098:
} else {
} else {
$print("Odd");
$print("Odd");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,695: Line 3,105:
=={{header|NESL}}==
=={{header|NESL}}==
NESL provides <tt>evenp</tt> and <tt>oddp</tt> functions, but they wouldn't be hard to reimplement.
NESL provides <tt>evenp</tt> and <tt>oddp</tt> functions, but they wouldn't be hard to reimplement.
<lang nesl>function even(n) = mod(n, 2) == 0;
<syntaxhighlight lang="nesl">function even(n) = mod(n, 2) == 0;


% test the function by applying it to the first ten positive integers: %
% test the function by applying it to the first ten positive integers: %
{even(n) : n in [1:11]};</lang>
{even(n) : n in [1:11]};</syntaxhighlight>
{{out}}
{{out}}
<pre>it = [F, T, F, T, F, T, F, T, F, T] : [bool]</pre>
<pre>it = [F, T, F, T, F, T, F, T, F, T] : [bool]</pre>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,746: Line 3,156:
else sv = 'Odd'
else sv = 'Odd'
return sv.left(4)
return sv.left(4)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,765: Line 3,175:


=={{header|Never}}==
=={{header|Never}}==
<syntaxhighlight lang="never">
<lang Never>
func isOdd(n : int) -> int {
func isOdd(n : int) -> int {
n % 2 == 1
n % 2 == 1
Line 2,773: Line 3,183:
n % 2 == 0
n % 2 == 0
}
}
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(odd? 1)
<syntaxhighlight lang="newlisp">(odd? 1)
(even? 2)</lang>
(even? 2)</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim># Least signficant bit:
<syntaxhighlight lang="nim"># Least signficant bit:
proc isOdd(i: int): bool = (i and 1) != 0
proc isOdd(i: int): bool = (i and 1) != 0
proc isEven(i: int): bool = (i and 1) == 0
proc isEven(i: int): bool = (i and 1) == 0
Line 2,793: Line 3,203:


echo isEven(1)
echo isEven(1)
echo isOdd2(5)</lang>
echo isOdd2(5)</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with|oo2c}}
{{works with|oo2c}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE EvenOrOdd;
MODULE EvenOrOdd;
IMPORT
IMPORT
S := SYSTEM,
S := SYSTEM,
Out;
Out;
Line 2,808: Line 3,218:
BEGIN
BEGIN
x := 10;Out.Int(x,0);
x := 10;Out.Int(x,0);
IF ODD(x) THEN Out.String(" odd") ELSE Out.String(" even") END;
IF ODD(x) THEN Out.String(" odd") ELSE Out.String(" even") END;
Out.Ln;
Out.Ln;


x := 11;s := S.VAL(SET,LONG(x));Out.Int(x,0);
x := 11;s := S.VAL(SET,LONG(x));Out.Int(x,0);
IF 0 IN s THEN Out.String(" odd") ELSE Out.String(" even") END;
IF 0 IN s THEN Out.String(" odd") ELSE Out.String(" even") END;
Out.Ln;
Out.Ln;


x := 12;Out.Int(x,0);
x := 12;Out.Int(x,0);
Line 2,819: Line 3,229:
Out.Ln
Out.Ln
END EvenOrOdd.
END EvenOrOdd.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,828: Line 3,238:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>a := Console->ReadString()->ToInt();
<syntaxhighlight lang="objeck">a := Console->ReadString()->ToInt();
if(a % 2 = 0) {
if(a % 2 = 0) {
"even"->PrintLine();
"even"->PrintLine();
Line 2,834: Line 3,244:
else {
else {
"odd"->PrintLine();
"odd"->PrintLine();
};</lang>
};</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Modulo:
Modulo:
<lang ocaml>let is_even d =
<syntaxhighlight lang="ocaml">let is_even d =
(d mod 2) = 0
(d mod 2) = 0


let is_odd d =
let is_odd d =
(d mod 2) <> 0</lang>
(d mod 2) <> 0</syntaxhighlight>
Bitwise and:
Bitwise and:
<lang ocaml>let is_even d =
<syntaxhighlight lang="ocaml">let is_even d =
(d land 1) = 0
(d land 1) = 0


let is_odd d =
let is_odd d =
(d land 1) <> 0</lang>
(d land 1) <> 0</syntaxhighlight>


An instructive view on functional programming and recursion:
An instructive view on functional programming and recursion:
<lang ocaml>(* hmm, only valid for N >= 0 *)
<syntaxhighlight lang="ocaml">(* hmm, only valid for N >= 0 *)
let rec myeven = function
let rec myeven = function
| 0 -> true
| 0 -> true
| 1 -> false
| 1 -> false
Line 2,858: Line 3,268:


(* and here we have the not function in if form *)
(* and here we have the not function in if form *)
let myodd n = if myeven n then false else true</lang>
let myodd n = if myeven n then false else true</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>12 isEven
<syntaxhighlight lang="oforth">12 isEven
12 isOdd</lang>
12 isOdd</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Actually, 'even?' and 'odd?' functions are built-in. But,
Actually, 'even?' and 'odd?' functions are built-in. But,


<lang scheme>
<syntaxhighlight lang="scheme">
; 1. Check the least significant bit.
; 1. Check the least significant bit.
(define (even? i)
(define (even? i)
Line 2,902: Line 3,312:
(print (if (odd? 1234567898765432) "odd" "even")) ; ==> even
(print (if (odd? 1234567898765432) "odd" "even")) ; ==> even


</syntaxhighlight>
</lang>


=={{header|OOC}}==
=={{header|OOC}}==
<lang ooc>
<syntaxhighlight lang="ooc">
// Using the modulo operator
// Using the modulo operator
even: func (n: Int) -> Bool {
even: func (n: Int) -> Bool {
Line 2,915: Line 3,325:
(n & 1) == 1
(n & 1) == 1
}
}
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
GP does not have a built-in predicate for testing parity, but it's easy to code:
GP does not have a built-in predicate for testing parity, but it's easy to code:
<lang parigp>odd(n)=n%2;</lang>
<syntaxhighlight lang="parigp">odd(n)=n%2;</syntaxhighlight>
Alternately:
Alternately:
<lang parigp>odd(n)=bitand(n,1);</lang>
<syntaxhighlight lang="parigp">odd(n)=bitand(n,1);</syntaxhighlight>
PARI can use the same method as [[#C|C]] for testing individual words. For multiprecision integers (t_INT), use <code>mpodd</code>. If the number is known to be nonzero, <code>mod2</code> is (insignificantly) faster.
PARI can use the same method as [[#C|C]] for testing individual words. For multiprecision integers (t_INT), use <code>mpodd</code>. If the number is known to be nonzero, <code>mod2</code> is (insignificantly) faster.


=={{header|Pascal}}==
=={{header|Pascal}}==
Built-in boolean function odd:
Built-in boolean function odd:
<lang pascal>isOdd := odd(someIntegerNumber);</lang>
<syntaxhighlight lang="pascal">isOdd := odd(someIntegerNumber);</syntaxhighlight>
bitwise and:
bitwise and:
<lang pascal>function isOdd(Number: integer): boolean
<syntaxhighlight lang="pascal">function isOdd(Number: integer): boolean
begin
begin
isOdd := boolean(Number and 1)
isOdd := boolean(Number and 1)
end;</lang>
end;</syntaxhighlight>
Dividing and multiplying by 2 and test on equality:
Dividing and multiplying by 2 and test on equality:
<lang pascal>function isEven(Number: integer): boolean
<syntaxhighlight lang="pascal">function isEven(Number: integer): boolean
begin
begin
isEven := (Number = ((Number div 2) * 2))
isEven := (Number = ((Number div 2) * 2))
end;</lang>
end;</syntaxhighlight>
Using built-in modulo
Using built-in modulo
<lang pascal>function isOdd(Number: integer): boolean
<syntaxhighlight lang="pascal">function isOdd(Number: integer): boolean
begin
begin
isOdd := boolean(Number mod 2)
isOdd := boolean(Number mod 2)
end;</lang>
end;</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>for(0..10){
<syntaxhighlight lang="perl">for(0..10){
print "$_ is ", qw(even odd)[$_ % 2],"\n";
print "$_ is ", qw(even odd)[$_ % 2],"\n";
}</lang>
}</syntaxhighlight>
or
or
<lang perl>print 6 % 2 ? 'odd' : 'even'; # prints even</lang>
<syntaxhighlight lang="perl">print 6 % 2 ? 'odd' : 'even'; # prints even</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
There are builtin routines odd() and even() which return true/false - note however they will round non-integer arguments to the nearest whole number, which might be confusing. The mpz_odd() and mpz_even() are similar, but without any way to pass them fractions. In fact odd() invokes and_bits(i,1)=1 and even() invokes and_bits(i,1)=0, so no difference there, and "i&&1" is just shorthand for and_bits(i,1). Lastly remainder(i,2) can also validly be used, however "true" for odd numbers is actually 1 for positive odd integers and -1 for negative odd integers, plus fractions are preserved, so "remainder(i,2)==0" is perhaps for some uses a more flexible and accurate "even"/"not even" test.
There are builtin routines odd() and even() which return true/false - note however they will round non-integer arguments to the nearest whole number, which might be confusing. The mpz_odd() and mpz_even() are similar, but without any way to pass them fractions. In fact odd() invokes and_bits(i,1)=1 and even() invokes and_bits(i,1)=0, so no difference there, and "i&&1" is just shorthand for and_bits(i,1). Lastly remainder(i,2) can also validly be used, however "true" for odd numbers is actually 1 for positive odd integers and -1 for negative odd integers, plus fractions are preserved, so "remainder(i,2)==0" is perhaps for some uses a more flexible and accurate "even"/"not even" test.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,961: Line 3,371:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d: %5t %5t %3d %5d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">even</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #000000;">i</span><span style="color: #0000FF;">&&</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d: %5t %5t %3d %5d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">odd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">even</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span><span style="color: #000000;">i</span><span style="color: #0000FF;">&&</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,979: Line 3,389:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>-5 5 2 tolist for
<syntaxhighlight lang="phixmonti">-5 5 2 tolist for
dup print " " print 2 mod if "Odd" else "Even" endif print nl
dup print " " print 2 mod if "Odd" else "Even" endif print nl
endfor</lang>
endfor</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
// using bitwise and to check least significant digit
// using bitwise and to check least significant digit
echo (2 & 1) ? 'odd' : 'even';
echo (2 & 1) ? 'odd' : 'even';
Line 2,992: Line 3,402:
echo (3 % 2) ? 'odd' : 'even';
echo (3 % 2) ? 'odd' : 'even';
echo (4 % 2) ? 'odd' : 'even';
echo (4 % 2) ? 'odd' : 'even';
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,002: Line 3,412:
=={{header|Picat}}==
=={{header|Picat}}==
{{works with|Picat}}
{{works with|Picat}}
<syntaxhighlight lang="picat">
<lang Picat>
% Bitwise and
% Bitwise and
is_even_bitwise(I) = cond(I /\ 1 == 0, true, false).
is_even_bitwise(I) = cond(I /\ 1 == 0, true, false).
Line 3,022: Line 3,432:
printf("%d is even? %s\n", I, yes_or_no(is_even_rem(I)))
printf("%d is even? %s\n", I, yes_or_no(is_even_rem(I)))
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,037: Line 3,447:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp doesn't have a built-in predicate for that. Using '[http://software-lab.de/doc/refB.html#bit? bit?]' is the easiest and most efficient. The bit test with 1 will return NIL if the number is even.
PicoLisp doesn't have a built-in predicate for that. Using '[http://software-lab.de/doc/refB.html#bit? 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)
<syntaxhighlight lang="picolisp">: (bit? 1 3)
-> 1 # Odd
-> 1 # Odd


: (bit? 1 4)
: (bit? 1 4)
-> NIL # Even</lang>
-> NIL # Even</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>> int i = 73;
<syntaxhighlight lang="pike">> int i = 73;
> (i&1);
> (i&1);
Result: 1
Result: 1
> i%2;
> i%2;
Result: 1</lang>
Result: 1</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>i = iand(i,1)</lang>
<syntaxhighlight lang="pl/i">i = iand(i,1)</syntaxhighlight>
The result is 1 when i is odd, and 0 when i is even.
The result is 1 when i is odd, and 0 when i is even.


Line 3,058: Line 3,468:
at all.
at all.


<lang plm>100H:
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 3,076: Line 3,486:


CALL EXIT;
CALL EXIT;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>0 IS EVEN
<pre>0 IS EVEN
Line 3,091: Line 3,501:
=={{header|Plain English}}==
=={{header|Plain English}}==
The noodle comes with even and odd deciders.
The noodle comes with even and odd deciders.
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
If 56 is even, write "56 is even!" to the console.
If 56 is even, write "56 is even!" to the console.
If 4 is odd, write "4 is odd!" to the console.
If 4 is odd, write "4 is odd!" to the console.
Wait for the escape key.
Wait for the escape key.
Shut down.</lang>
Shut down.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,106: Line 3,516:
===Predicate===
===Predicate===
A predicate can be used with BigInteger objects. Even/odd predicates to not exist for basic value types. Type accelerator [bigint] can be used in place of [System.Numerics.BigInteger].
A predicate can be used with BigInteger objects. Even/odd predicates to not exist for basic value types. Type accelerator [bigint] can be used in place of [System.Numerics.BigInteger].
<syntaxhighlight lang="powershell">
<lang PowerShell>
$IsOdd = -not ( [bigint]$N ).IsEven
$IsOdd = -not ( [bigint]$N ).IsEven
$IsEven = ( [bigint]$N ).IsEven
$IsEven = ( [bigint]$N ).IsEven
</syntaxhighlight>
</lang>
===Least significant digit===
===Least significant digit===
<syntaxhighlight lang="powershell">
<lang PowerShell>
$IsOdd = [boolean]( $N -band 1 )
$IsOdd = [boolean]( $N -band 1 )
$IsEven = [boolean]( $N -band 0 )
$IsEven = [boolean]( $N -band 0 )
</syntaxhighlight>
</lang>
===Remainder===
===Remainder===
Despite being known as a modulus operator, the % operator in PowerShell actually returns a remainder. As such, when testing negative numbers it returns the true modulus result minus M. In this specific case, it returns -1 for odd negative numbers. Thus we test for not zero for odd numbers.
Despite being known as a modulus operator, the % operator in PowerShell actually returns a remainder. As such, when testing negative numbers it returns the true modulus result minus M. In this specific case, it returns -1 for odd negative numbers. Thus we test for not zero for odd numbers.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$IsOdd = $N % 2 -ne 0
$IsOdd = $N % 2 -ne 0
$IsEven = $N % 2 -eq 0
$IsEven = $N % 2 -eq 0
</syntaxhighlight>
</lang>


=={{header|Processing}}==
=={{header|Processing}}==
<syntaxhighlight lang="processing">
<lang Processing>
boolean isEven(int i){
boolean isEven(int i){
return i%2 == 0;
return i%2 == 0;
Line 3,131: Line 3,541:
return i%2 == 1;
return i%2 == 1;
}
}
</syntaxhighlight>
</lang>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 3,137: Line 3,547:
to test whether the integer N is even. To illustrate, here is a predicate that can
to test whether the integer N is even. To illustrate, here is a predicate that can
be used both to test whether an integer is even and to generate the non-negative even numbers:
be used both to test whether an integer is even and to generate the non-negative even numbers:
<lang prolog>
<syntaxhighlight lang="prolog">
even(N) :-
even(N) :-
(between(0, inf, N); integer(N) ),
(between(0, inf, N); integer(N) ),
0 is N mod 2.
0 is N mod 2.
</syntaxhighlight>
</lang>
===Least Significant Bit===
===Least Significant Bit===
If N is a positive integer, then lsb(N) is the offset of its least significant bit, so we could write:
If N is a positive integer, then lsb(N) is the offset of its least significant bit, so we could write:
<lang prolog>
<syntaxhighlight lang="prolog">
odd(N) :- N = 0 -> false; 0 is lsb(abs(N)).
odd(N) :- N = 0 -> false; 0 is lsb(abs(N)).
</syntaxhighlight>
</lang>

=={{header|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>


=={{header|Python}}==
=={{header|Python}}==
===Python: Using the least-significant bit method===
===Python: Using the least-significant bit method===
<lang python>>>> def is_odd(i): return bool(i & 1)
<syntaxhighlight lang="python">>>> def is_odd(i): return bool(i & 1)


>>> def is_even(i): return not is_odd(i)
>>> def is_even(i): return not is_odd(i)
Line 3,167: Line 3,568:
>>> [(j, is_even(j)) for j in range(10)]
>>> [(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)]
[(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)]
>>> </lang>
>>> </syntaxhighlight>


===Python: Using modular congruences===
===Python: Using modular congruences===
<lang python>>> def is_even(i):
<syntaxhighlight lang="python">>> def is_even(i):
return (i % 2) == 0
return (i % 2) == 0


Line 3,177: Line 3,578:
>>> is_even(2)
>>> is_even(2)
True
True
>>></lang>
>>></syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang quackery>[ 1 & ] is odd ( n --> b )
<syntaxhighlight lang="quackery">[ 1 & ] is odd ( n --> b )


[ odd not ] is even ( n --> b )</lang>
[ odd not ] is even ( n --> b )</syntaxhighlight>
{{out}}
{{out}}
In the Quackery shell (REPL):
In the Quackery shell (REPL):
Line 3,201: Line 3,602:
See also [https://rosettacode.org/wiki/Mutual_recursion#Quackery Mutual recursion#Quackery] and [https://rosettacode.org/wiki/Anonymous_recursion#Quackery Anonymous recursion#Quackery].
See also [https://rosettacode.org/wiki/Mutual_recursion#Quackery Mutual recursion#Quackery] and [https://rosettacode.org/wiki/Anonymous_recursion#Quackery Anonymous recursion#Quackery].


<lang Quackery> [ abs
<syntaxhighlight lang="quackery"> [ abs

' [ dup 0 = iff
' [ dup 0 = iff
[ 2drop true ] done
[ 2drop true ] done
1 - this swap rot do ] ( x n --> b )
1 - this swap rot do ] ( x n --> b )

' [ dup 0 = iff
' [ dup 0 = iff
[ 2drop false ] done
[ 2drop false ] done
1 - this swap rot do ] ( x n --> b )
1 - this swap rot do ] ( x n --> b )

unrot do ] is even ( n --> b )
unrot do ] is even ( n --> b )


11 times
11 times
[ i^ 5 - dup echo
[ i^ 5 - dup echo
say " is "
say " is "
even iff [ $ "even" ]
even iff [ $ "even" ]
else [ $ "odd" ]
else [ $ "odd" ]
echo$ say "." cr ] </lang>
echo$ say "." cr ] </syntaxhighlight>


{{out}}
{{out}}
Line 3,235: Line 3,636:


=={{header|R}}==
=={{header|R}}==
<lang R>is.even <- function(x) !is.odd(x)
<syntaxhighlight lang="r">is.even <- function(x) !is.odd(x)


is.odd <- function(x) intToBits(x)[1] == 1
is.odd <- function(x) intToBits(x)[1] == 1
#or
#or
is.odd <- function(x) x %% 2 == 1</lang>
is.odd <- function(x) x %% 2 == 1</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
With built in predicates:
With built in predicates:
<lang Racket>(even? 6) ; -> true
<syntaxhighlight lang="racket">(even? 6) ; -> true
(even? 5) ; -> false
(even? 5) ; -> false
(odd? 6) ; -> false
(odd? 6) ; -> false
(odd? 5) ; -> true </lang>
(odd? 5) ; -> true </syntaxhighlight>


With modular arithmetic:
With modular arithmetic:
<lang Racket>(define (my-even? x)
<syntaxhighlight lang="racket">(define (my-even? x)
(= (modulo x 2) 0))
(= (modulo x 2) 0))


(define (my-odd? x)
(define (my-odd? x)
(= (modulo x 2) 1))</lang>
(= (modulo x 2) 1))</syntaxhighlight>

With mutually recursive functions:
<syntaxhighlight lang="racket">
(define (even-or-odd? i)
(letrec ([even? (λ (n)
(if (= n 0)
'even
(odd? (sub1 n))))]
[odd? (λ (n)
(if (= n 0)
'odd
(even? (sub1 n))))])
(even? i)))

(even-or-odd? 100) ; => 'even
(even-or-odd? 101) ; => 'odd
</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Raku doesn't have a built-in for this, but with subsets it's easy to define a predicate for it.
Raku 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;
<syntaxhighlight lang="raku" line>subset Even of Int where * %% 2;
subset Odd of Int where * % 2;
subset Odd of Int where * % 2;


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


=={{header|Rascal}}==
=={{header|Rascal}}==
<lang rascal>public bool isEven(int n) = (n % 2) == 0;
<syntaxhighlight lang="rascal">public bool isEven(int n) = (n % 2) == 0;
public bool isOdd(int n) = (n % 2) == 1;</lang>
public bool isOdd(int n) = (n % 2) == 1;</syntaxhighlight>
Or with block quotes:
Or with block quotes:
<lang rascal>public bool isEven(int n){return (n % 2) == 0;}
<syntaxhighlight lang="rascal">public bool isEven(int n){return (n % 2) == 0;}
public bool isOdd(int n){return (n % 2) == 1;}</lang>
public bool isOdd(int n){return (n % 2) == 1;}</syntaxhighlight>

=={{header|RATFOR}}==
<syntaxhighlight lang="ratfor">
program evenodd

integer a

write(*,101,ADVANCE="NO")
read(*,102)a

if (mod(a,2) .eq. 0) write(*,103)a
else write(*,104)a


101 format("Enter a number: ")
102 format(i7)
103 format(i7," Is Even.")
104 format(i7," Is Odd.")


end
</syntaxhighlight>

=={{header|Rapira}}==
<syntaxhighlight lang="rapira">fun is_even(n)
return (n /% 2) = 0
end</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang red>Red [
<syntaxhighlight lang="red">Red [
date: 2021-10-24
date: 2021-10-24
red-version: 0.6.4
red-version: 0.6.4
Line 3,280: Line 3,725:


print even? 10 ;== true
print even? 10 ;== true
print odd? 10 ;== false</lang>
print odd? 10 ;== false</syntaxhighlight>


=={{header|ReScript}}==
=={{header|ReScript}}==


<lang rescript>let is_even = d => mod(d, 2) == 0
<syntaxhighlight lang="rescript">let is_even = d => mod(d, 2) == 0

let is_odd = d => mod(d, 2) != 0</lang>
let is_odd = d => mod(d, 2) != 0</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 3,292: Line 3,737:
:::* by removing a superfluous leading &nbsp; '''+''' &nbsp; sign
:::* by removing a superfluous leading &nbsp; '''+''' &nbsp; sign
:::* by removing superfluous leading zeroes
:::* by removing superfluous leading zeroes
:::* by removing superfluous trailing zeroes
:::* by removing superfluous trailing zeroes
:::* by removing a trailing decimal point
:::* by removing a trailing decimal point
:::* possible converting an exponentiated number
:::* possible converting an exponentiated number
:::* possible rounding the number to the current ''digits''
:::* possible rounding the number to the current ''digits''


'''Programming note''': &nbsp; the last method is the fastest method in REXX to determine oddness/evenness.
'''Programming note''': &nbsp; the last method is the fastest method in REXX to determine oddness/evenness.
<br>It requires a sparse stemmed array &nbsp; &nbsp; '''!.''' &nbsp; &nbsp; be defined in the program's prologue (or elsewhere).
<br>It requires a sparse stemmed array &nbsp; &nbsp; '''!.''' &nbsp; &nbsp; be defined in the program's prologue (or elsewhere).
<br>This method gets its speed from &nbsp; ''not'' &nbsp; using any BIF and &nbsp; ''not'' &nbsp; performing any (remainder) division.
<br>This method gets its speed from &nbsp; ''not'' &nbsp; using any BIF and &nbsp; ''not'' &nbsp; performing any (remainder) division.


'''Some notes on programming styles''': &nbsp;
'''Some notes on programming styles''': &nbsp;
If (execution) speed isn't an issue, then the 1<sup>st</sup> test method
If (execution) speed isn't an issue, then the 1<sup>st</sup> test method
<br>shown would be the simplest &nbsp; (in terms of coding the concisest/tightest/smallest code). &nbsp; The other test
<br>shown would be the simplest &nbsp; (in terms of coding the concisest/tightest/smallest code). &nbsp; The other test
<br>methods differ mostly in programming techniques, mostly depending on the REXX programmer's style. &nbsp;
<br>methods differ mostly in programming techniques, mostly depending on the REXX programmer's style. &nbsp;
<br>The last method shown is the fastest algorithm, albeit it might be a bit obtuse (without comments) to a
<br>The last method shown is the fastest algorithm, albeit it might be a bit obtuse (without comments) to a
<br>novice reader of the REXX language &nbsp; (and it requires additional REXX statement baggage).
<br>novice reader of the REXX language &nbsp; (and it requires additional REXX statement baggage).
<lang rexx>/*REXX program tests and displays if an integer is even or odd using different styles.*/
<syntaxhighlight lang="rexx">/*REXX program tests and displays if an integer is even or odd using different styles.*/
!.=0; do j=0 by 2 to 8; !.j=1; end /*assign 0,2,4,6,8 to a "true" value.*/
!.=0; do j=0 by 2 to 8; !.j=1; end /*assign 0,2,4,6,8 to a "true" value.*/
/* [↑] assigns even digits to "true".*/
/* [↑] assigns even digits to "true".*/
Line 3,382: Line 3,827:
odd: return arg(1)//2 /*returns "oddness" of the argument. */
odd: return arg(1)//2 /*returns "oddness" of the argument. */
tell: say; say center('using the' arg(1), 79, "═"); return
tell: say; say center('using the' arg(1), 79, "═"); return
terr: say; say '***error***'; say; say arg(1); say; exit 13</lang>
terr: say; say '***error***'; say; say arg(1); say; exit 13</syntaxhighlight>
'''output''' &nbsp; when using the input of: &nbsp; <tt> 0 </tt>
'''output''' &nbsp; when using the input of: &nbsp; <tt> 0 </tt>
<pre>
<pre>
Line 3,439: Line 3,884:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
size = 10
size = 10
for i = 1 to size
for i = 1 to size
Line 3,445: Line 3,890:
else see "" + i + " is even" + nl ok
else see "" + i + " is even" + nl ok
next
next
</syntaxhighlight>
</lang>

=={{header|RPL}}==
To test oddity of real numbers (floating point numbers) :
≪ 2 MOD ≫ ‘ODD?’ STO
To test oddity of binary integers (unsigned integers) :
≪ #1 AND #1 ≠ ≫ ‘BODD?’ STO
To test oddity without caring of the data type :
≪ IF DUP TYPE THEN #1 AND #1 ≠ ELSE 2 MOD END ≫
{{in}}
<pre>
47 ODD?
#Fh BODD?
</pre>
{{out}}
<pre>
2: 1
1: 1
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
In Ruby, integers behave like objects, so they respond to methods like : 5.even? resulting to false

<lang ruby>print "evens: "
<syntaxhighlight lang="ruby">print "evens: "
p -5.upto(5).select(&:even?)
p -5.upto(5).select(&:even?)
print "odds: "
print "odds: "
p -5.upto(5).select(&:odd?)</lang>
p -5.upto(5).select(&:odd?)</syntaxhighlight>
{{out}}
{{out}}
<pre>evens: [-4, -2, 0, 2, 4]
<pre>evens: [-4, -2, 0, 2, 4]
odds: [-5, -3, -1, 1, 3, 5]</pre>
odds: [-5, -3, -1, 1, 3, 5]</pre>
Other ways to test even-ness:
Other ways to test even-ness:
<lang ruby>n & 1 == 0
<syntaxhighlight lang="ruby">n & 1 == 0
quotient, remainder = n.divmod(2); remainder == 0
quotient, remainder = n.divmod(2); remainder == 0


Line 3,466: Line 3,929:
# You can use the bracket operator to access the i'th bit
# You can use the bracket operator to access the i'th bit
# of a Fixnum or Bignum (i = 0 means least significant bit)
# of a Fixnum or Bignum (i = 0 means least significant bit)
n[0].zero?</lang>
n[0].zero?</syntaxhighlight>

=={{header|Run BASIC}}==
{{works with|QBasic}}
<lang runbasic>for i = 1 to 10
if i and 1 then print i;" is odd" else print i;" is even"
next i</lang>
<pre>
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
</pre>


=={{header|Rust}}==
=={{header|Rust}}==
Checking the least significant digit:
Checking the least significant digit:
<lang rust>let is_odd = |x: i32| x & 1 == 1;
<syntaxhighlight lang="rust">let is_odd = |x: i32| x & 1 == 1;
let is_even = |x: i32| x & 1 == 0;</lang>
let is_even = |x: i32| x & 1 == 0;</syntaxhighlight>


Using modular congruences:
Using modular congruences:
<lang rust>let is_odd = |x: i32| x % 2 != 0;
<syntaxhighlight lang="rust">let is_odd = |x: i32| x % 2 != 0;
let is_even = |x: i32| x % 2 == 0;</lang>
let is_even = |x: i32| x % 2 == 0;</syntaxhighlight>

=={{header|S-BASIC}}==
S-BASIC lacks a MOD operator but supports bitwise operations on integer variables, so that is the approach taken.
<lang basic>
rem - return true (-1) if even, otherwise false (0)
function even(i = integer) = integer
var one = integer rem - both operands must be variables
one = 1
end = ((i and one) = 0)

rem - exercise the function
var i = integer
for i = 1 to 10 step 3
print i; " is ";
if even(i) then
print "even"
else
print "odd"
next

end</lang>
{{out}}
<pre>
1 is odd
4 is even
7 is odd
10 is even</pre>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def isEven( v:Int ) : Boolean = v % 2 == 0
<syntaxhighlight lang="scala">def isEven( v:Int ) : Boolean = v % 2 == 0
def isOdd( v:Int ) : Boolean = v % 2 != 0</lang>
def isOdd( v:Int ) : Boolean = v % 2 != 0</syntaxhighlight>
Accept any numeric type as an argument:
Accept any numeric type as an argument:
<lang scala>def isEven( v:Number ) : Boolean = v.longValue % 2 == 0
<syntaxhighlight lang="scala">def isEven( v:Number ) : Boolean = v.longValue % 2 == 0
def isOdd( v:Number ) : Boolean = v.longValue % 2 != 0</lang>
def isOdd( v:Number ) : Boolean = v.longValue % 2 != 0</syntaxhighlight>
{{out}}
{{out}}
<pre>isOdd( 81 ) // Results in true
<pre>isOdd( 81 ) // Results in true
Line 3,535: Line 3,953:
=={{header|Scheme}}==
=={{header|Scheme}}==
<code>even?</code> and <code>odd?</code> functions are built-in (R<sup>4</sup>RS, R<sup>5</sup>RS, and R<sup>6</sup>RS):
<code>even?</code> and <code>odd?</code> functions are built-in (R<sup>4</sup>RS, R<sup>5</sup>RS, and R<sup>6</sup>RS):
<lang scheme>> (even? 5)
<syntaxhighlight lang="scheme">> (even? 5)
#f
#f
> (even? 42)
> (even? 42)
Line 3,542: Line 3,960:
#t
#t
> (odd? 42)
> (odd? 42)
#f</lang>
#f</syntaxhighlight>

=={{header|sed}}==
<syntaxhighlight lang="sed">s/[02468]$/& is even/
s/[13579]$/& is odd/</syntaxhighlight>
{{out}}
<pre>$ seq -18 7 17 | sed -f even_or_odd.sed
-18 is even
-11 is odd
-4 is even
3 is odd
10 is even
17 is odd</pre>


=={{header|Seed7}}==
=={{header|Seed7}}==
Test whether an integer or bigInteger is odd:
Test whether an integer or bigInteger is odd:
<lang seed7>odd(aNumber)</lang>
<syntaxhighlight lang="seed7">odd(aNumber)</syntaxhighlight>
Test whether an integer or bigInteger is even:
Test whether an integer or bigInteger is even:
<lang seed7>not odd(aNumber)</lang>
<syntaxhighlight lang="seed7">not odd(aNumber)</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set num to random of 100 -- start with a random number from 1 to 100
set num to random of 100 -- start with a random number from 1 to 100


Line 3,562: Line 3,992:
// check to see if the remainder is 0 when dividing by 2
// check to see if the remainder is 0 when dividing by 2
if num rem 2 is 0 then put num & " is even (zero remainder)"
if num rem 2 is 0 then put num & " is even (zero remainder)"
</syntaxhighlight>
</lang>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<lang sequencel>even(x) := x mod 2 = 0;
<syntaxhighlight lang="sequencel">even(x) := x mod 2 = 0;
odd(x) := x mod 2 = 1;</lang>
odd(x) := x mod 2 = 1;</syntaxhighlight>


{{out}}
{{out}}
Line 3,578: Line 4,008:
=={{header|SETL}}==
=={{header|SETL}}==
SETL provides built-in <tt>even</tt> and <tt>odd</tt> functions. This short program illustrates their use.
SETL provides built-in <tt>even</tt> and <tt>odd</tt> functions. This short program illustrates their use.
<lang setl>xs := {1..10};
<syntaxhighlight lang="setl">xs := {1..10};
evens := {x in xs | even( x )};
evens := {x in xs | even( x )};
odds := {x in xs | odd( x )};
odds := {x in xs | odd( x )};
print( evens );
print( evens );
print( odds );</lang>
print( odds );</syntaxhighlight>
{{out}}
{{out}}
<pre>{2 4 6 8 10}
<pre>{2 4 6 8 10}
Line 3,590: Line 4,020:


Mutual Recursion:
Mutual Recursion:
<lang shen>(define even?
<syntaxhighlight lang="shen">(define even?
0 -> true
0 -> true
X -> (odd? (- X 1)))
X -> (odd? (- X 1)))
Line 3,596: Line 4,026:
(define odd?
(define odd?
0 -> false
0 -> false
X -> (even? (- X 1)))</lang>
X -> (even? (- X 1)))</syntaxhighlight>


Modulo:
Modulo:
<lang shen>(define even? X -> (= 0 (shen.mod X 2)))
<syntaxhighlight lang="shen">(define even? X -> (= 0 (shen.mod X 2)))


(define odd? X -> (not (= 0 (shen.mod X 2))))</lang>
(define odd? X -> (not (= 0 (shen.mod X 2))))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Built-in methods:
Built-in methods:
<lang ruby>var n = 42;
<syntaxhighlight lang="ruby">var n = 42;
say n.is_odd; # false
say n.is_odd; # false
say n.is_even; # true</lang>
say n.is_even; # true</syntaxhighlight>


Checking the last significant digit:
Checking the last significant digit:
<lang ruby>func is_odd(n) { n&1 == 1 };
<syntaxhighlight lang="ruby">func is_odd(n) { n&1 == 1 };
func is_even(n) { n&1 == 0 };</lang>
func is_even(n) { n&1 == 0 };</syntaxhighlight>


Using modular congruences:
Using modular congruences:
<lang ruby>func is_odd(n) { n%2 == 1 };
<syntaxhighlight lang="ruby">func is_odd(n) { n%2 == 1 };
func is_even(n) { n%2 == 0 };</lang>
func is_even(n) { n%2 == 0 };</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 3,621: Line 4,051:
Using the built in methods on Number class:
Using the built in methods on Number class:


<lang smalltalk>5 even
<syntaxhighlight lang="smalltalk">5 even
5 odd</lang>
5 odd</syntaxhighlight>


even is implemented as follows:
even is implemented as follows:
<lang smalltalk>Number>>even
<syntaxhighlight lang="smalltalk">Number>>even
^((self digitAt: 1) bitAnd: 1) = 0
^((self digitAt: 1) bitAnd: 1) = 0
</syntaxhighlight>
</lang>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 3,633: Line 4,063:
{{works with|Spitbol}}
{{works with|Spitbol}}
{{Works with|SNOBOL4+}}
{{Works with|SNOBOL4+}}
<lang SNOBOL4> DEFINE('even(n)') :(even_end)
<syntaxhighlight lang="snobol4"> DEFINE('even(n)') :(even_end)
even even = (EQ(REMDR(n, 2), 0) 'even', 'odd') :(RETURN)
even even = (EQ(REMDR(n, 2), 0) 'even', 'odd') :(RETURN)
even_end
even_end
Line 3,642: Line 4,072:
OUTPUT = "1 is " even(1)
OUTPUT = "1 is " even(1)
OUTPUT = "2 is " even(2)
OUTPUT = "2 is " even(2)
END</lang>
END</syntaxhighlight>
{{output}}<pre>-2 is even
{{output}}<pre>-2 is even
-1 is odd
-1 is odd
Line 3,651: Line 4,081:


=={{header|SNUSP}}==
=={{header|SNUSP}}==
<syntaxhighlight lang="snusp">
<lang SNUSP>
$====!/?\==even#
$====!/?\==even#
- -
- -
#odd==\?/
#odd==\?/
</syntaxhighlight>
</lang>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>> n, 0..9
<syntaxhighlight lang="spl">> n, 0..9
? #.even(n), #.output(n," even")
? #.even(n), #.output(n," even")
? #.odd(n), #.output(n," odd")
? #.odd(n), #.output(n," odd")
<</lang>
<</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,678: Line 4,108:
=={{header|SQL}}==
=={{header|SQL}}==
Database vendors can't agree on how to get a remainder. This should work for many, including Oracle. For others, including MS SQL Server, try "int % 2" instead of "mod(int, 2)".
Database vendors can't agree on how to get a remainder. This should work for many, including Oracle. For others, including MS SQL Server, try "int % 2" instead of "mod(int, 2)".
<lang sql>-- Setup a table with some integers
<syntaxhighlight lang="sql">-- Setup a table with some integers
create table ints(int integer);
create table ints(int integer);
insert into ints values (-1);
insert into ints values (-1);
Line 3,690: Line 4,120:
case mod(int, 2) when 0 then 'Even' else 'Odd' end
case mod(int, 2) when 0 then 'Even' else 'Odd' end
from
from
ints;</lang>
ints;</syntaxhighlight>


{{out}}
{{out}}
Line 3,707: Line 4,137:


For larger positive or smaller negative values of <math>n</math>, you should be ready with something else to do while the machine is working: a test run took several minutes to confirm that 32,769 was odd.
For larger positive or smaller negative values of <math>n</math>, you should be ready with something else to do while the machine is working: a test run took several minutes to confirm that 32,769 was odd.
<lang ssem>11110000000000100000000000000000 0. -15 to c
<syntaxhighlight lang="ssem">11110000000000100000000000000000 0. -15 to c
00000000000000110000000000000000 1. Test
00000000000000110000000000000000 1. Test
11110000000001100000000000000000 2. c to 15
11110000000001100000000000000000 2. c to 15
Line 3,721: Line 4,151:
00000000000001110000000000000000 12. Stop
00000000000001110000000000000000 12. Stop
10000000000000000000000000000000 13. 1
10000000000000000000000000000000 13. 1
01000000000000000000000000000000 14. 2</lang>
01000000000000000000000000000000 14. 2</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun even n =
<syntaxhighlight lang="sml">fun even n =
n mod 2 = 0;
n mod 2 = 0;


fun odd n =
fun odd n =
n mod 2 <> 0;
n mod 2 <> 0;


Line 3,734: Line 4,164:
type werd = Word.word;
type werd = Word.word;


fun evenbitw(w: werd) =
fun evenbitw(w: werd) =
Word.andb(w, 0w2) = 0w0;
Word.andb(w, 0w2) = 0w0;


fun oddbitw(w: werd) =
fun oddbitw(w: werd) =
Word.andb(w, 0w2) <> 0w0;</lang>
Word.andb(w, 0w2) <> 0w0;</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>mata
<syntaxhighlight lang="stata">mata
function iseven(n) {
function iseven(n) {
return(mod(n,2)==0)
return(mod(n,2)==0)
Line 3,749: Line 4,179:
return(mod(n,2)==1)
return(mod(n,2)==1)
}
}
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>func isEven(n:Int) -> Bool {
<syntaxhighlight lang="swift">func isEven(n:Int) -> Bool {

// Bitwise check
// Bitwise check
if (n & 1 != 0) {
if (n & 1 != 0) {
return false
return false
}
}

// Mod check
// Mod check
if (n % 2 != 0) {
if (n % 2 != 0) {
Line 3,764: Line 4,194:
}
}
return true
return true
}</lang>
}</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="swift">
// Swift has Int.isMultiple(of:Int) -> Bool

var isEven: (_:Int) -> Bool = {$0.isMultiple(of: 2)}
</syntaxhighlight>


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<lang symsyn>
<syntaxhighlight lang="symsyn">
n : 23
n : 23


Line 3,774: Line 4,210:
else
else
'n is even' []
'n is even' []
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


# Bitwise test is the most efficient
# Bitwise test is the most efficient
Line 3,785: Line 4,221:
puts " # O E"
puts " # O E"
puts 24:[expr isOdd(24)],[expr isEven(24)]
puts 24:[expr isOdd(24)],[expr isEven(24)]
puts 49:[expr isOdd(49)],[expr isEven(49)]</lang>
puts 49:[expr isOdd(49)],[expr isEven(49)]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,793: Line 4,229:
</pre>
</pre>


=={{header|TI-83 BASIC}}==
=={{header|TI-57}}==
This routine returns the remainder of the division by 2 of the number in the display register. It is therefore a kind of is_odd(x) function.
TI-83 BASIC does not have a modulus operator.
Lbl 9
<lang ti83b>
/
If fPart(.5Ans
2
Then
-
Disp "ODD
CE
Else
Int
Disp "EVEN
=
End
×
</lang>
2
=
INV SBR


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
LOOP n=-5,5
LOOP n=-5,5
x=MOD(n,2)
x=MOD(n,2)
Line 3,814: Line 4,253:
PRINT n," is odd"
PRINT n," is odd"
ENDSELECT
ENDSELECT
ENDLOOP</lang>
ENDLOOP</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,831: Line 4,270:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<syntaxhighlight lang="sh">is_even() {
<lang shell>iseven() {
[[ $(($1%2)) -eq 0 ]] && return 0
return $(($1 & 1))
}</syntaxhighlight>
return 1
}</lang>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl int input
<syntaxhighlight lang="ursa">decl int input
set input (in int console)
set input (in int console)
if (= (mod input 2) 1)
if (= (mod input 2) 1)
Line 3,843: Line 4,281:
else
else
out "even" endl console
out "even" endl console
end if</lang>
end if</syntaxhighlight>
Output:
Output:
<pre>123
<pre>123
Line 3,849: Line 4,287:


=={{header|உயிர்/Uyir}}==
=={{header|உயிர்/Uyir}}==
<lang உயிர்/Uyir>முதன்மை என்பதின் வகை எண் பணி {{
<syntaxhighlight lang="உயிர்/uyir">முதன்மை என்பதின் வகை எண் பணி {{
எ இன் வகை எண்{$5} = 0;
எ இன் வகை எண்{$5} = 0;
படை வகை சரம்;
படை வகை சரம்;
Line 3,866: Line 4,304:


முதன்மை = 0;
முதன்மை = 0;
}};</lang>
}};</syntaxhighlight>

=={{header|VBA}}==
<pre>
4 ways = 4 Functions :
IsEven ==> Use the even and odd predicates
IsEven2 ==> Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even
IsEven3 ==> Divide i by 2. The remainder equals 0 if i is even.
IsEven4 ==> Use modular congruences</pre>

<lang vb>
Option Explicit

Sub Main_Even_Odd()
Dim i As Long

For i = -50 To 48 Step 7
Debug.Print i & " : IsEven ==> " & IIf(IsEven(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven2 ==> " & IIf(IsEven2(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven3 ==> " & IIf(IsEven3(i), "is even", "is odd") _
& " " & Chr(124) & " IsEven4 ==> " & IIf(IsEven4(i), "is even", "is odd")
Next
End Sub

Function IsEven(Number As Long) As Boolean
'Use the even and odd predicates
IsEven = (WorksheetFunction.Even(Number) = Number)
End Function

Function IsEven2(Number As Long) As Boolean
'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.
Dim lngTemp As Long
lngTemp = CLng(Right(CStr(Number), 1))
If (lngTemp And 1) = 0 Then IsEven2 = True
End Function

Function IsEven3(Number As Long) As Boolean
'Divide i by 2.
'The remainder equals 0 if i is even.
Dim sngTemp As Single
sngTemp = Number / 2
IsEven3 = ((Int(sngTemp) - sngTemp) = 0)
End Function

Function IsEven4(Number As Long) As Boolean
'Use modular congruences
IsEven4 = (Number Mod 2 = 0)
End Function
</lang>
{{out}}
<pre>-50 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-43 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-36 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-29 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-22 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-15 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-8 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-1 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
6 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
13 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
20 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
27 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
34 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
41 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
48 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even</pre>

=={{header|VBScript}}==
<lang vb>
Function odd_or_even(n)
If n Mod 2 = 0 Then
odd_or_even = "Even"
Else
odd_or_even = "Odd"
End If
End Function

WScript.StdOut.Write "Please enter a number: "
n = WScript.StdIn.ReadLine
WScript.StdOut.Write n & " is " & odd_or_even(CInt(n))
WScript.StdOut.WriteLine
</lang>

{{Out}}
<pre>
C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 6
6 is Even

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 9
9 is Odd

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: -1
-1 is Odd
</pre>


=={{header|Verilog}}==
=={{header|Verilog}}==
<lang Verilog>module main;
<syntaxhighlight lang="verilog">module main;
integer i;
integer i;

initial begin
initial begin
for (i = 1; i <= 10; i = i+1) begin
for (i = 1; i <= 10; i = i+1) begin
Line 3,975: Line 4,317:
$finish ;
$finish ;
end
end
endmodule</lang>
endmodule</syntaxhighlight>


=={{header|Visual Basic .NET}}==
{{trans|FreeBASIC}}
<lang vbnet>Module Module1

Sub Main()
Dim str As String
Dim num As Integer
While True
Console.Write("Enter an integer or 0 to finish: ")
str = Console.ReadLine()
If Integer.TryParse(str, num) Then
If num = 0 Then
Exit While
End If
If num Mod 2 = 0 Then
Console.WriteLine("Even")
Else
Console.WriteLine("Odd")
End If
Else
Console.WriteLine("Bad input.")
End If
End While
End Sub

End Module</lang>
=== BigInteger ===
{{Libheader|System.Numerics}}
<lang vbnet>Imports System.Numerics

Module Module1
  Function IsOdd(bi As BigInteger) As Boolean
Return Not bi.IsEven
End Function

Function IsEven(bi As BigInteger) As Boolean
Return bi.IsEven
End Function

Sub Main()
' uncomment one of the following Dim statements
' Dim x As Byte = 3
' Dim x As Short = 3
' Dim x As Integer = 3
' Dim x As Long = 3
' Dim x As SByte = 3
' Dim x As UShort = 3
' Dim x As UInteger = 3
' Dim x As ULong = 3
' Dim x as BigInteger = 3
' the following three types give a warning, but will work
' Dim x As Single = 3
' Dim x As Double = 3
' Dim x As Decimal = 3

Console.WriteLine("{0} {1}", IsOdd(x), IsEven(x))
End Sub
End Module</lang>


=={{header|Vlang}}==
=={{header|V (Vlang)}}==
<lang vlang>fn test(n i64) {
<syntaxhighlight lang="v (vlang)">fn test(n i64) {
print('Testing integer $n')
print('Testing integer $n')


Line 4,060: Line 4,342:
test(1)
test(1)
test(2)
test(2)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,071: Line 4,353:


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let s => import 'stream';
<syntaxhighlight lang="wdte">let s => import 'stream';
let str => import 'strings';
let str => import 'strings';


Line 4,085: Line 4,367:
-> s.map (@ s n => str.format '{} is {}.' n (evenOrOdd n))
-> s.map (@ s n => str.format '{} is {}.' n (evenOrOdd n))
-> s.map (io.writeln io.stdout)
-> s.map (io.writeln io.stdout)
-> s.drain;</lang>
-> s.drain;</syntaxhighlight>


=={{header|WebAssembly}}==
=={{header|WebAssembly}}==
This solution tests the low bit of the given integer, which is always 0 for even numbers and 1 for odd numbers (including negative numbers).
This solution tests the low bit of the given integer, which is always 0 for even numbers and 1 for odd numbers (including negative numbers).


<lang WebAssembly>(module
<syntaxhighlight lang="webassembly">(module
;; function isOdd: returns 1 if its argument is odd, 0 if it is even.
;; function isOdd: returns 1 if its argument is odd, 0 if it is even.
(func $isOdd (param $n i32) (result i32)
(func $isOdd (param $n i32) (result i32)
Line 4,098: Line 4,380:
)
)
(export "isOdd" (func $isOdd))
(export "isOdd" (func $isOdd))
)</lang>
)</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="wren">import "./fmt" for Fmt


var isEven1 = Fn.new { |i| i & 1 == 0 }
var isEven1 = Fn.new { |i| i & 1 == 0 }
Line 4,113: Line 4,395:
System.print("Method 1 : %(Fmt.v("s", -4, res1, 0, " ", ""))")
System.print("Method 1 : %(Fmt.v("s", -4, res1, 0, " ", ""))")
var res2 = tests.map { |t| isEven2.call(t) ? "even" : "odd" }.toList
var res2 = tests.map { |t| isEven2.call(t) ? "even" : "odd" }.toList
System.print("Method 2 : %(Fmt.v("s", -4, res2, 0, " ", ""))")</lang>
System.print("Method 2 : %(Fmt.v("s", -4, res2, 0, " ", ""))")</syntaxhighlight>


{{out}}
{{out}}
Line 4,123: Line 4,405:


=={{header|x86-64 Assembly}}==
=={{header|x86-64 Assembly}}==
<lang x86_64 Assembly>
<syntaxhighlight lang="x86_64 assembly">
evenOdd:
evenOdd:
mov rax,1
mov rax,1
and rax,rdi
and rax,rdi
ret
ret
</syntaxhighlight>
</lang>


=={{header|XBS}}==
=={{header|XBS}}==
<syntaxhighlight lang="xbs">#>
<lang XBS>#>
Typed XBS
Typed XBS
evenOrOdd function
evenOrOdd function
Line 4,143: Line 4,425:
foreach(v of arr){
foreach(v of arr){
log(v+" is even? "+evenOrOdd(v))
log(v+" is even? "+evenOrOdd(v))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,159: Line 4,441:


=={{header|xEec}}==
=={{header|xEec}}==
<syntaxhighlight lang="xeec">
<lang xEec>
>100 p i# jz-1 o# t h#1 ms jz2003 p >0110 h#2 r ms t h#1 ms p
>100 p i# jz-1 o# t h#1 ms jz2003 p >0110 h#2 r ms t h#1 ms p
jz1002 h? jz2003 p jn0110 h#10 o$ p jn100 >2003 p p h#0 h#10
jz1002 h? jz2003 p jn0110 h#10 o$ p jn100 >2003 p p h#0 h#10
h$d h$d h$o h#32 h$s h$i h#32 jn0000 >1002 p p h#0 h#10
h$d h$d h$o h#32 h$s h$i h#32 jn0000 >1002 p p h#0 h#10
h$n h$e h$v h$e h#32 h$s h$i h#32 >0000 o$ p jn0000 jz100
h$n h$e h$v h$e h#32 h$s h$i h#32 >0000 o$ p jn0000 jz100
</syntaxhighlight>
</lang>


=={{header|XLISP}}==
=={{header|XLISP}}==
XLISP provides <tt>EVENP</tt> and <tt>ODDP</tt>, or, if you prefer, <tt>EVEN?</tt> and <tt>ODD?</tt>; if one wanted to reimplement them, it could be done like this (or in other ways).
XLISP provides <tt>EVENP</tt> and <tt>ODDP</tt>, or, if you prefer, <tt>EVEN?</tt> and <tt>ODD?</tt>; if one wanted to reimplement them, it could be done like this (or in other ways).
<lang lisp>(defun my-evenp (x)
<syntaxhighlight lang="lisp">(defun my-evenp (x)
(= (logand x 1) 0) )
(= (logand x 1) 0) )


(defun my-oddp (x)
(defun my-oddp (x)
(/= (logand x 1) 0) )</lang>
(/= (logand x 1) 0) )</syntaxhighlight>


=={{header|Xojo}}==
=={{header|Xojo}}==
<syntaxhighlight lang="vb">
<lang vb>
For num As Integer = 1 To 5
For num As Integer = 1 To 5
If num Mod 2 = 0 Then
If num Mod 2 = 0 Then
Line 4,183: Line 4,465:
End If
End If
Next
Next
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,195: Line 4,477:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int I;
int I;
[for I:= -4 to +3 do
[for I:= -4 to +3 do
[IntOut(0, I);
[IntOut(0, I);
Text(0, if I&1 then " is odd " else " is even ");
Text(0, if I&1 then " is odd " else " is even ");
Text(0, if rem(I/2)#0 then "odd" else "even");
Text(0, if rem(I/2)#0 then "odd" else "even");
CrLf(0);
CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,216: Line 4,498:
3 is odd odd
3 is odd odd
</pre>
</pre>

=={{header|Yabasic}}==
{{trans|Phix}}
<lang Yabasic>for i = -5 to 5
print i, and(i,1), mod(i,2)
next
</lang>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
Z80 Assembly has a few ways of testing if a number is even or odd:
Z80 Assembly has a few ways of testing if a number is even or odd:
===RRC===
===RRC===
A right rotate will set the carry if the register's value is odd and clear it if it's even. This does alter the contents of the register, so only use this method if you don't need to remember the number being tested after getting the results of the test.
A right rotate will set the carry if the register's value is odd and clear it if it's even. This does alter the contents of the register, so only use this method if you don't need to remember the number being tested after getting the results of the test. This is the fastest way the Z80 can test a value for even or odd, but only when testing the accumulator <tt>A</tt>
<lang z80>rrca
<syntaxhighlight lang="z80">rrca
jp nc,isEven</lang>
jp nc,isEven</syntaxhighlight>

===SRA/SRL===
In similar vein, there are also shift instructions. The arithmetic shift instruction retains the sign bit (bit 7) of the operand in question, while the logical shift sets bit 7 to 0.
<syntaxhighlight lang="z80">sra a
jp nc,isEven</syntaxhighlight>


===AND===
===AND===
<code>AND 1</code> will change the accumulator to 1 if its value was odd, and 0 if its value was even. If you want to selectively load a 0 or 1 into the accumulator based on whether a variable is odd or even, this is the best way to do so. Like the <code>RRC</code> method, this test is destructive, so if you need to preserve the original value of the accumulator after the test, use the method below instead.
<code>AND 1</code> will change the accumulator to 1 if its value was odd, and 0 if its value was even. If you want to selectively load a 0 or 1 into the accumulator based on whether a variable is odd or even, this is the best way to do so. Like the <code>RRC</code> method, this test is destructive, so if you need to preserve the original value of the accumulator after the test, use the method below instead.
<lang z80>and &01
<syntaxhighlight lang="z80">and &01
jp z,isEven</lang>
jp z,isEven</syntaxhighlight>


===BIT===
===BIT===
This method is the slowest, but it doesn't change the value in the register being tested. It works on any 8 bit register, (HL), (IX+#), or (IY+#), making it the most versatile. Although I say it's the slowest, the difference is so small and the execution time so fast that you'd never notice anyway. The Z80 can perform all these tests faster than you can blink!
This method is the slowest, but it doesn't change the value in the register being tested. It works on any 8 bit register, (HL), (IX+#), or (IY+#), making it the most versatile. Although I say it's the slowest, the difference is so small and the execution time so fast that you'd never notice anyway. The Z80 can perform all these tests faster than you can blink!
<lang z80>bit 0,c
<syntaxhighlight lang="z80">bit 0,c
jp z,C_IS_EVEN</lang>
jp z,C_IS_EVEN</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>[-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") })</lang>
<syntaxhighlight lang="zkl">[-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") })</syntaxhighlight>
Ints have isEven and isOdd properties. pump, in this case, is the same as apply/map without aggregating a result.
Ints have isEven and isOdd properties. pump, in this case, is the same as apply/map without aggregating a result.
{{out}}
{{out}}
Line 4,255: Line 4,535:
4 is even
4 is even
</pre>
</pre>
<lang zkl>[-3..4].apply("isEven").println();</lang>
<syntaxhighlight lang="zkl">[-3..4].apply("isEven").println();</syntaxhighlight>
{{out}}
{{out}}
<pre>L(False,True,False,True,False,True,False,True)</pre>
<pre>L(False,True,False,True,False,True,False,True)</pre>


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: even_or_odd
program: even_or_odd
case: 1
case: 1
Line 4,274: Line 4,554:
input: 7
input: 7
output: odd
output: odd
</syntaxhighlight>
</lang>


=={{header|Zoea Visual}}==
=={{header|Zoea Visual}}==
Line 4,280: Line 4,560:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module Main;
module Main;
var
var
Line 4,291: Line 4,571:
s := set(x);writeln(x:3," is odd?",0 in s); (* check right bit *)
s := set(x);writeln(x:3," is odd?",0 in s); (* check right bit *)
end Main.
end Main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,299: Line 4,579:
11 is odd? true
11 is odd? true
</pre>
</pre>

=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 FOR n=-3 TO 4: GO SUB 30: NEXT n
20 STOP
30 LET odd=FN m(n,2)
40 PRINT n;" is ";("Even" AND odd=0)+("Odd" AND odd=1)
50 RETURN
60 DEF FN m(a,b)=a-INT (a/b)*b</lang>

Latest revision as of 18:00, 1 March 2024

Task
Even or odd
You are encouraged to solve this task according to the task description, using any language you may know.
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.



0815

}:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65:
x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s:

11l

F is_even(i)
   R i % 2 == 0

F is_odd(i)
   R i % 2 == 1

6502 Assembly

        .lf  evenodd6502.lst
        .cr  6502
        .tf  evenodd6502.obj,ap1
;------------------------------------------------------
; Even or Odd for the 6502 by barrym95838 2014.12.10
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
;   mixed-case output capabilities.  Apple IIs like to
;   work in '+128' ascii, and this version is tailored
;   to that preference.
; Tested and verified on AppleWin 1.20.0.0
;------------------------------------------------------
; Constant Section
;
CharIn   =   $fd0c      ;Specific to the Apple II
CharOut  =   $fded      ;Specific to the Apple II
;------------------------------------------------------
; The main program
;
main    ldy  #sIntro-sbase
        jsr  puts       ;Print Intro
loop    jsr  CharIn     ;Get a char from stdin
        cmp  #$83       ;Ctrl-C?
        beq  done       ;  yes:  end program
        jsr  CharOut    ;Echo char
        ldy  #sOdd-sbase ;Pre-load odd string
        lsr             ;LSB of char to carry flag
        bcs  isodd
        ldy  #sEven-sbase
isodd   jsr  puts       ;Print appropriate response
        beq  loop       ;Always taken
; Output NUL-terminated string @ offset Y
;
puts    lda  sbase,y    ;Get string char
        beq  done       ;Done if NUL
        jsr  CharOut    ;Output the char
        iny             ;Point to next char
        bne  puts       ;Loop up to 255 times
done    rts             ;Return to caller
;------------------------------------------------------
; String Constants (in '+128' ascii, Apple II style)
;
sbase:                  ;String base address
sIntro  .az     -"Hit any key (Ctrl-C to quit):",-#13
sEven   .az     -" is even.",-#13
sOdd    .az     -" is odd.",-#13
;------------------------------------------------------
        .en

68000 Assembly

Non-Destructive

BTST D0,#1
BNE isOdd
;else, is even.

Destructive

AND.B D0,#1
BNE isOdd
;else, is even.
ROR.B D0,#1
BCS isOdd
;else, is even.
ROXR.B D0,#1
BCS isOdd
;else, is even.
LSR.B D0,#1
BCS isOdd
;else, is even.
ASR.B D0,#1
BCS isOdd
;else, is even.


You can also use BCLR,BSET, and BCHG in the same way you use BTST, as all of them copy the affected bit to the zero flag. BCLR,BSET, and BCHG will change the value of that bit after the test, so keep that in mind.

8080 Assembly

The instruction that's doing all the work here is rar, which is a bitwise right rotate of the accumulator through the carry flag. That leaves the low bit in the carry flag, which will be set if odd and clear if even.

CMDLIN:	equ	80h		; Location of CP/M command line argument
puts:	equ	9h		; Syscall to print a string
	;;;	Check if number given on command line is even or odd
	org	100h
	lxi	h,CMDLIN	; Find length of argument
	mov	a,m
	add	l		; Look up last character (digit)
	mov	l,a
	mov	a,m		; Retrieve low digit
	rar			; Rotate low bit into carry flag
	mvi	c,puts		; Prepare to print string
	lxi	d,odd		; If carry is set, then the number is odd
	jc	5		; So print 'odd'
	lxi	d,even		; Otherwise, the number is even
	jmp 	5		; So print 'even'
even:	db	'Even$'		; Strings
odd:	db	'Odd$'
Output:
A>evenodd 0
Even
A>evenodd 1
Odd
A>evenodd 2
Even
A>evenodd 3141592653
Odd
A>

8086 Assembly

Non-Destructive

test ax,1
jne isOdd
;else, is even

Destructive

and ax,1
jne isOdd
;else, is even
ror ax,1
jc isOdd
;else, is even
rcr ax,1
jc isOdd
;else, is even
sar ax,1
jc isOdd
;else, is even
shr ax,1
jc isOdd
;else, is even

The DIV instruction can also work, but using DIV to divide by 2 is a waste of time, since the shift and rotate commands above do it faster.

8th

The 'mod' method also works, but the bit method is fastest.

: odd? \ n -- boolean
    dup 1 n:band 1 n:= ;
: even? \ n -- boolean
    odd? not ;

This could be shortened to:

: even? \ n -- f
  1 n:band not ;
: odd? \ n -- f
  even? not ;

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B and android arm 64 bits*/
/*  program oddEven64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResultOdd:        .asciz " @ is odd (impair) \n"
sMessResultEven:       .asciz " @ is even (pair)  \n"
szCarriageReturn:      .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:        .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                 //entry of program

    mov x0,#5
    bl testOddEven
    mov x0,#12
    bl testOddEven
    mov x0,#2021
    bl testOddEven
100:                                  //standard end of the program
    mov x0, #0                        //return code
    mov x8, #EXIT                     //request to exit program
    svc #0                            //perform the system call

qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResultOdd:       .quad sMessResultOdd
qAdrsMessResultEven:      .quad sMessResultEven
qAdrsZoneConv:            .quad sZoneConv
/***************************************************/
/*     test if number is odd or even               */
/***************************************************/
// x0 contains à number
testOddEven:
    stp x1,lr,[sp,-16]!       // save  registres
    tst x0,#1                   //test bit 0 to one
    beq 1f                      //if result are all zéro, go to even
    ldr x1,qAdrsZoneConv        //else display odd message
    bl conversion10             //call decimal conversion
    ldr x0,qAdrsMessResultOdd
    ldr x1,qAdrsZoneConv        //insert value conversion in message
    bl strInsertAtCharInc
    bl affichageMess
    b 100f
1:
    ldr x1,qAdrsZoneConv
    bl conversion10             //call decimal conversion
    ldr x0,qAdrsMessResultEven
    ldr x1,qAdrsZoneConv        //insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess
100:
    ldp x1,lr,[sp],16         // restaur des  2 registres
    ret
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Output:
 5 is odd (impair)
 12 is even (pair)
 2021 is odd (impair)

ABAP

cl_demo_output=>display(
  VALUE string_table(
    FOR i = -5 WHILE i < 6 (
      COND string(
        LET r = i MOD 2 IN
        WHEN r = 0 THEN |{ i } is even|
        ELSE |{ i } is odd|
      )
    )
  )
).
Output:
Table 
-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 

Action!

PROC OddByAnd(INT v)
  IF (v&1)=0 THEN
    Print(" even")
  ELSE
    Print(" odd ")
  FI
RETURN

PROC OddByMod(INT v)
  ;MOD doesn't work properly for negative numbers in Action!
  IF v<0 THEN
    v=-v
  FI
  IF v MOD 2=0 THEN
    Print(" even")
  ELSE
    Print(" odd ")
  FI
RETURN

PROC OddByDiv(INT v)
  INT d
  d=(v/2)*2
  IF v=d THEN
    Print(" even")
  ELSE
    Print(" odd ")
  FI
RETURN

PROC Main()
  INT i

  FOR i=-4 TO 4
  DO
    PrintF("%I is",i)
    OddByAnd(i)
    OddByMod(i)
    OddByDiv(i)
    PutE()
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

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

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;

Agda

module EvenOrOdd where

open import Data.Bool using (Bool; false; true)
open import Data.Nat using (ℕ; zero; suc)

even :   Bool
odd  :   Bool

even zero    = true
even (suc n) = odd n

odd zero    = false
odd (suc n) = even n

Aime

if (x & 1) {
    # x is odd
} else {
    # x is even
}

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.win32
# Algol 68 has a standard operator: ODD which returns TRUE if its integer  #
# operand is odd and FALSE if it is even                                   #
# E.g.:                                                                    #

INT n;
print( ( "Enter an integer: " ) );
read( ( n ) );
print( ( whole( n, 0 ), " is ", IF ODD n THEN "odd" ELSE "even" FI, newline ) )

ALGOL-M

Because ALGOL-M lacks a built-in MOD operator or function and does not support bitwise operations on integers, the test is a bit cumbersome, but gets the job done.

BEGIN

% RETURN 1 IF EVEN, OTHERWISE 0 %
INTEGER FUNCTION EVEN(I);
INTEGER I;
BEGIN
  EVEN := 1 - (I - 2 * (I / 2));
END;

% TEST THE ROUTINE %
INTEGER K;
FOR K := 1 STEP 3 UNTIL 10 DO
  WRITE(K," IS ", IF EVEN(K) = 1 THEN "EVEN" ELSE "ODD");

END
Output:
    1 IS ODD
    4 IS EVEN
    7 IS ODD
   10 IS EVEN

An alternate (but mathematically equivalent) coding, demonstrating the use of a conditional test as part of an assignment statement:

% RETURN 1 IF EVEN, OTHERWISE 0 %
INTEGER FUNCTION EVEN(I);
INTEGER I;
BEGIN
  EVEN := (IF I = 2 * (I / 2) THEN 1 ELSE 0);
END;

ALGOL W

begin
    % the Algol W standard procedure odd returns true if its integer  %
    % parameter is odd, false if it is even                           %
    for i := 1, 1702, 23, -26
    do begin
        write( i, " is ", if odd( i ) then "odd" else "even" )
    end for_i
end.
Output:
             1   is odd
          1702   is even
            23   is odd
           -26   is even

AntLang

odd: {x mod 2}
even: {1 - x mod 2}

APL

The easiest way is probably to use modulo.

      2|28
0
      2|37
1

So you can write a user-defined operator.

     odd ← 2∘|

AppleScript

set L to {3, 2, 1, 0, -1, -2, -3}

set evens to {}
set odds to {}

repeat with x in L
    if (x mod 2 = 0) then
        set the end of evens to x's contents
    else
        set the end of odds to x's contents
    end if
end repeat

return {even:evens, odd:odds}
Output:
{even:{2, 0, -2}, odd:{3, 1, -1, -3}}


Or, packaging reusable functions that can serve as arguments to filter, partition etc (deriving even from mod, and odd from even):

----------------------- EVEN OR ODD ------------------------

-- even :: Int -> Bool
on even(n)
    0 = n mod 2
end even

-- odd :: Int -> Bool
on odd(n)
    not even(n)
end odd


--------------------------- TEST ---------------------------
on run
    
    partition(odd, enumFromTo(-6, 6))
    
    --> {{-5, -3, -1, 1, 3, 5}, {-6, -4, -2, 0, 2, 4, 6}}
end run


-------------------- GENERICS FOR TEST ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m  n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        lst
    else
        {}
    end if
end enumFromTo



-- partition :: (a -> Bool) -> [a] -> ([a], [a])
on partition(p, xs)
    tell mReturn(p)
        set {ys, zs} to {{}, {}}
        repeat with x in xs
            set v to contents of x
            if |λ|(v) then
                set end of ys to v
            else
                set end of zs to v
            end if
        end repeat
    end tell
    {ys, zs}
end partition


-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{{-5, -3, -1, 1, 3, 5}, {-6, -4, -2, 0, 2, 4, 6}}

Arendelle

( input , "Please enter a number: " )

{ @input % 2 = 0 ,

	"| @input | is even!"
,
	"| @input | is odd!"
}

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  or android 32 bits */
/*  program oddEven.s   */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResultOdd:        .asciz " @  is odd (impair) \n"
sMessResultEven:       .asciz " @  is even (pair)  \n"
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:        .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                 @ entry of program

    mov r0,#5
    bl testOddEven
    mov r0,#12
    bl testOddEven
    mov r0,#2021
    bl testOddEven
100:                                  @ standard end of the program
    mov r0, #0                        @ return code
    mov r7, #EXIT                     @ request to exit program
    svc #0                            @ perform the system call

iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResultOdd:       .int sMessResultOdd
iAdrsMessResultEven:      .int sMessResultEven
iAdrsZoneConv:            .int sZoneConv
/***************************************************/
/*     test if number is odd or even               */
/***************************************************/
// r0 contains à number
testOddEven:
    push {r2-r8,lr}             @ save  registers
    tst r0,#1                   @ test bit 0 to one
    beq 1f                      @ if result are all zéro, go to even
    ldr r1,iAdrsZoneConv        @ else display odd message
    bl conversion10             @ call decimal conversion
    ldr r0,iAdrsMessResultOdd
    ldr r1,iAdrsZoneConv        @ insert value conversion in message
    bl strInsertAtCharInc
    bl affichageMess
    b 100f
1:
    ldr r1,iAdrsZoneConv
    bl conversion10             @ call decimal conversion
    ldr r0,iAdrsMessResultEven
    ldr r1,iAdrsZoneConv        @ insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess
100:
    pop {r2-r8,lr}             @ restaur registers
    bx lr                      @ return
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"

ArnoldC

LISTEN TO ME VERY CAREFULLY isOdd
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE result
YOU SET US UP @I LIED
GET TO THE CHOPPER result
HERE IS MY INVITATION n
I LET HIM GO 2
ENOUGH TALK
I'LL BE BACK result
HASTA LA VISTA, BABY

LISTEN TO ME VERY CAREFULLY showParity
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
TALK TO THE HAND n
HEY CHRISTMAS TREE parity
YOU SET US UP @I LIED
GET YOUR A** TO MARS parity
DO IT NOW isOdd n
BECAUSE I'M GOING TO SAY PLEASE parity
TALK TO THE HAND "odd"
BULLS***
TALK TO THE HAND "even"
YOU HAVE NO RESPECT FOR LOGIC
TALK TO THE HAND ""
HASTA LA VISTA, BABY

IT'S SHOWTIME
DO IT NOW showParity 5
DO IT NOW showParity 6
DO IT NOW showParity -11
YOU HAVE BEEN TERMINATED
Output:
5
odd

6
even

-11
odd

Arturo

loop (neg 5)..5 [x][
	if? even? x -> print [pad to :string x 4 ": even"]
	else -> print [pad to :string x 4 ": odd"]
]
Output:
  -5 : odd 
  -4 : even 
  -3 : odd 
  -2 : even 
  -1 : odd 
   0 : even 
   1 : odd 
   2 : even 
   3 : odd 
   4 : even 
   5 : odd


Asymptote

for (int i = 1; i <= 10; ++i)  {
  if (i % 2 == 0) {
    write(string(i), " is even");
  } else {
    write(string(i), " is odd");
  }
}


AutoHotkey

Bitwise ops are probably most efficient:

if ( int & 1 ){
	; do odd stuff
}else{
	; do even stuff
}

AWK

function isodd(x) {
	return x % 2 != 0
}

function iseven(x) {
	return x % 2 == 0
}

BASIC

Applesoft 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
Works with: Commodore BASIC version 2.0

BaCon

' Even or odd
OPTION MEMTYPE int
SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim
n = IIF$(dim < 2, 0, VAL(arg$[1]))
PRINT n, " is ", IIF$(EVEN(n), "even", "odd")
Output:
prompt$ ./even-or-odd 42
42 is even
prompt$ ./even-or-odd 41
41 is odd

BASIC256

Works with: True BASIC
for i = 1 to 10
  if (i mod 2) then print i;" is odd" else print i;" is even"
next i
end

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.

      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)
Output:
14 is even
15 is odd
9876543210 is even
9876543211 is odd

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4

Uses bitwise AND as suggested.

10 cls
20 for n = 1 to 10
30  print n;
40  if (n and 1) = 1 then print "is odd" else print "is even"
50  next n
60 end

Commodore BASIC

Uses bitwise AND as suggested.

10 rem determine if integer is even or odd
20 print "Enter an integer:";
30 input i%
35 print
40 eo$="even"
50 if (i% and 1)=1 then eo$="odd"
60 print "The number ";i%;"is ";eo$;"."

FreeBASIC

' FB 1.05.0 Win64

Dim n As Integer

Do
  Print "Enter an integer or 0 to finish : ";
  Input "", n
  If n = 0 Then
    Exit Do
  ElseIf n Mod 2 = 0 Then
    Print "Your number is even"
    Print
  Else
    Print "Your number is odd"
    Print
  End if
Loop

End

Gambas

Public Sub Form_Open()
Dim sAnswer, sMessage As String

sAnswer = InputBox("Input an integer", "Odd or even")

If IsInteger(sAnswer) Then
  If Odd(Val(sAnswer)) Then sMessage = "' is an odd number"
  If Even(Val(sAnswer)) Then sMessage = "' is an even number"
Else
  sMessage = "' does not compute!!"
Endif

Print "'" & sAnswer & sMessage

End

Output:

'25' is an odd number
'100' is an even number
'Fred' does not compute!!

GW-BASIC

10 INPUT "Enter a number: ", N
20 IF N MOD 2 = 1 THEN PRINT "It is odd." ELSE PRINT "It is even."

IS-BASIC

100 DEF ODD(X)=MOD(X,2)
110 INPUT PROMPT "Enter a number: ":X
120 IF ODD(X) THEN
130   PRINT X;"is odd."
140 ELSE
150   PRINT X;"is even."
160 END IF

Liberty BASIC

Works with: Just BASIC
n=12

if n mod 2 = 0 then print "even" else print "odd"

Minimal BASIC

Works with: IS-BASIC
10 REM Even or odd
20 PRINT "Enter an integer number";
30 INPUT N
40 IF N/2 <> INT(N/2) THEN 70
50 PRINT "The number is even."
60 GOTO 80
70 PRINT "The number is odd."
80 END

MSX Basic

Uses bitwise AND as suggested.

10 CLS
20 FOR N = -5 TO 5
30 PRINT N;
40 IF (N AND 1) = 1 THEN PRINT "is odd" ELSE PRINT "is even"
50 NEXT N
60 END

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

QB64

NB: Line numbers are not required in this language. Further, because of the Int variable type used for input, floating point values will not be accepted by the program. 0 is a problem, though, as it returns "Even" in the code below, even though it is not mathematically an even value. For code brevity, the 0 problem is not addressed. Finally, No Even or Odd predicates exist in this language.

'This is a comment line. It also could have been preceded with "Rem"

Dim i%          'This line is not necessary, but % strict casts
                'as an Int (2 bytes). "As Int" could have been used instead.
Input "#? ", i% 'Prints "#? " as a prompt and waits
                'for user input terminated by pressing [ENTER].

'Binary integers example
If i% And 1 Then 'Test whether the input value AND 1 is 0 (false) or 1 (true).
                 'There is no global or constant "True" or "False".
    Print "Odd"  'Prints "Odd" if the above tested "true".
Else             'This could have been also been "ElseIf Not (i% And 1)"
    Print "Even" 'Prints "Even in all other cases (Else)
                 'or if the logical inverse of the input value AND 1 tested
                 '"true" (ElseIf).
End If

'Modular congruence example
If i% Mod 2 Then
    Print "Still Odd"
Else
    Print "Still Even"
End If

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
Works with: Run BASIC
FOR i = 1 TO 10
  IF i AND 1 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
NEXT i

Quite BASIC

10 CLS
20 FOR n = -5 TO 5
30  PRINT n;
40  IF n % 2 <> 0 THEN PRINT " is odd" ELSE PRINT " is even"
50  NEXT n
60 END

Run BASIC

Works with: QBasic
for i = 1 to 10
  if i and 1 then print i;" is odd" else print i;" is even"
next i
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

S-BASIC

S-BASIC lacks a MOD operator but supports bitwise operations on integer variables, so that is the approach taken.

rem - return true (-1) if even, otherwise false (0)
function even(i = integer) = integer
var one = integer    rem - both operands must be variables
one = 1
end = ((i and one) = 0)

rem - exercise the function
var i = integer
for i = 1 to 10 step 3
   print i; " is ";
   if even(i) then
     print "even"
   else
     print "odd"
next

end
Output:
 1 is odd
 4 is even
 7 is odd
 10 is even

TI-83 BASIC

TI-83 BASIC does not have a modulus operator.

If fPart(.5Ans
Then
Disp "ODD
Else
Disp "EVEN
End

Tiny BASIC

Works with: TinyBasic
10 PRINT "Enter a number:"
20 INPUT N
30 IF 2*(N/2) = N THEN GOTO 60
40 PRINT "It's odd."
50 END
60 PRINT "It's even."
70 END

True BASIC

Works with: BASIC256
FOR i = 1 to 10
    IF MOD(i, 2) = 0 THEN PRINT i; " is odd" ELSE PRINT i; " is even"
NEXT i
END

VBA

4 ways = 4 Functions :
IsEven ==> Use the even and odd predicates
IsEven2 ==> Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even
IsEven3 ==> Divide i by 2. The remainder equals 0 if i is even.
IsEven4 ==> Use modular congruences
Option Explicit

Sub Main_Even_Odd()
Dim i As Long

    For i = -50 To 48 Step 7
        Debug.Print i & " : IsEven ==> " & IIf(IsEven(i), "is even", "is odd") _
         & " " & Chr(124) & " IsEven2 ==> " & IIf(IsEven2(i), "is even", "is odd") _
         & " " & Chr(124) & " IsEven3 ==> " & IIf(IsEven3(i), "is even", "is odd") _
         & " " & Chr(124) & " IsEven4 ==> " & IIf(IsEven4(i), "is even", "is odd")
    Next
End Sub

Function IsEven(Number As Long) As Boolean
'Use the even and odd predicates
    IsEven = (WorksheetFunction.Even(Number) = Number)
End Function

Function IsEven2(Number As Long) As Boolean
'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.
Dim lngTemp As Long
    lngTemp = CLng(Right(CStr(Number), 1))
    If (lngTemp And 1) = 0 Then IsEven2 = True
End Function

Function IsEven3(Number As Long) As Boolean
'Divide i by 2.
'The remainder equals 0 if i is even.
Dim sngTemp As Single
    sngTemp = Number / 2
    IsEven3 = ((Int(sngTemp) - sngTemp) = 0)
End Function

Function IsEven4(Number As Long) As Boolean
'Use modular congruences
    IsEven4 = (Number Mod 2 = 0)
End Function
Output:
-50 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-43 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-36 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-29 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-22 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-15 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
-8 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
-1 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
6 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
13 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
20 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
27 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
34 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even
41 : IsEven ==> is odd | IsEven2 ==> is odd | IsEven3 ==> is odd | IsEven4 ==> is odd
48 : IsEven ==> is even | IsEven2 ==> is even | IsEven3 ==> is even | IsEven4 ==> is even

VBScript

Function odd_or_even(n)
	If n Mod 2 = 0 Then
		odd_or_even = "Even"
	Else
		odd_or_even = "Odd"
	End If
End Function

WScript.StdOut.Write "Please enter a number: "
n = WScript.StdIn.ReadLine
WScript.StdOut.Write n & " is " & odd_or_even(CInt(n))
WScript.StdOut.WriteLine
Output:
C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 6
6 is Even

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: 9
9 is Odd

C:\>cscript /nologo odd_or_even.vbs
Please enter a number: -1
-1 is Odd

Visual Basic .NET

Translation of: FreeBASIC
Module Module1

    Sub Main()
        Dim str As String
        Dim num As Integer
        While True
            Console.Write("Enter an integer or 0 to finish: ")
            str = Console.ReadLine()
            If Integer.TryParse(str, num) Then
                If num = 0 Then
                    Exit While
                End If
                If num Mod 2 = 0 Then
                    Console.WriteLine("Even")
                Else
                    Console.WriteLine("Odd")
                End If
            Else
                Console.WriteLine("Bad input.")
            End If
        End While
    End Sub

End Module

BigInteger

Imports System.Numerics

Module Module1
  Function IsOdd(bi As BigInteger) As Boolean
    Return Not bi.IsEven
  End Function

  Function IsEven(bi As BigInteger) As Boolean
    Return bi.IsEven
  End Function

  Sub Main()
    ' uncomment one of the following Dim statements
    ' Dim x As Byte = 3
    ' Dim x As Short = 3
    ' Dim x As Integer = 3
    ' Dim x As Long = 3
    ' Dim x As SByte = 3
    ' Dim x As UShort = 3
    ' Dim x As UInteger = 3
    ' Dim x As ULong = 3
    ' Dim x as BigInteger = 3
    ' the following three types give a warning, but will work
    ' Dim x As Single = 3
    ' Dim x As Double = 3
    ' Dim x As Decimal = 3

    Console.WriteLine("{0} {1}", IsOdd(x), IsEven(x))
  End Sub
End Module

XBasic

Works with: Windows XBasic
PROGRAM	"Even/Odd"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
  FOR i = 1 TO 10
    IF (i MOD 2) THEN PRINT i;" is odd" ELSE PRINT i;" is even"
  NEXT i
END FUNCTION

END PROGRAM

Yabasic

Translation of: Phix
for i = -5 to 5
    print i, and(i,1), mod(i,2)
next

ZX Spectrum Basic

10 FOR n=-3 TO 4: GO SUB 30: NEXT n
20 STOP
30 LET odd=FN m(n,2)
40 PRINT n;" is ";("Even" AND odd=0)+("Odd" AND odd=1)
50 RETURN
60 DEF FN m(a,b)=a-INT (a/b)*b

Batch File

@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

bc

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

i = -3

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

Beads

beads 1 program 'Even or odd'

calc main_init
	loop across:[-10, -5, 10, 5] val:v
		log "{v}\todd:{is_odd(v)}\teven:{is_even(v)}"
Output:
-10	odd:N	even:Y
-5	odd:Y	even:N
10	odd:N	even:Y
5	odd:Y	even:N

Befunge

&2%52**"E"+,@

Outputs E if even, O if odd.

Binary Lambda Calculus

In lambda calculus, the oddness of a given church numeral n can be computed as n applications of not to false: \n. n (\b\x\y. b y x) (\x\y.y), which in BLC is

00 01 01 10 0000000101111010110 000010

To compute the evenness, one need only replace false by true, i.e. replace the final 0 bit by 10.

BQN

odd  2|

!0  odd 12
!1  odd 31

Bracmat

Not the simplest solution, but the cheapest if the number that must be tested has thousands of digits.

( ( 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
)
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.

,[>,----------] 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

If one need only determine rather than act on the parity of the input, the following is sufficient; it terminates either quickly or never.

,[>,----------]<[--]

Burlesque

2.%

C

Test by bitwise and'ing 1, works for any builtin integer type as long as it's 2's complement (it's always so nowadays):

if (x & 1) {
    /* x is odd */
} else {
    /* or not */
}

If using long integer type from GMP (mpz_t), there are provided macros:

mpz_t x;
...
if (mpz_even_p(x)) { /* x is even */ }
if (mpz_odd_p(x))  { /* x is odd */ }

The macros evaluate x more than once, so it should not be something with side effects.

C#

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;
        }
    }
    public class Program
    {
        public static void Main()
        {
            int num = 26;               //Set this to any integer.
            if (num.IsEvenBitwise())    //Replace this with any even function.
            {
                Console.Write("Even");
            }
            else
            {
                Console.Write("Odd");
            }
            //Prints "Even".
            if (num.IsOddBitwise())    //Replace this with any odd function.
            {
                Console.Write("Odd");
            }
            else
            {
                Console.Write("Even");
            }
            //Prints "Even".
        }
    }
}

C++

Test using the modulo operator, or use the C example from above.

bool isOdd(int x)
{
    return x % 2;
}

bool isEven(int x)
{
    return !(x % 2);
}

A slightly more type-generic version, for C++11 and later. This should theoretically work for any type convertible to int:

template < typename T >
constexpr inline bool isEven( const T& v )
{
    return isEven( int( v ) );
}

template <>
constexpr inline bool isEven< int >( const int& v )
{
    return (v & 1) == 0;
}

template < typename T >
constexpr inline bool isOdd( const T& v )
{
    return !isEven(v);
}

Clojure

Standard predicates:

(if (even? some-var) (do-even-stuff))
(if (odd? some-var) (do-odd-stuff))

COBOL

       IF FUNCTION REM(Num, 2) = 0
           DISPLAY Num " is even."
       ELSE
           DISPLAY Num " is odd."
       END-IF

CoffeeScript

isEven = (x) -> !(x%2)

ColdFusion

function f(numeric n) {
   return n mod 2?"odd":"even"
}

Common Lisp

Standard predicates:

(if (evenp some-var) (do-even-stuff))
(if (oddp some-other-var) (do-odd-stuff))

Alternate solution

I use Allegro CL 10.1

;; Project : Even or odd

(defun evenodd (nr)
          (cond ((evenp nr) "even")
          ((oddp nr) "odd")))
(dotimes (n 10)
(if (< n 1) (terpri))
(if (< n 9) (format t "~a" " "))
(write(+ n 1)) (format t "~a" ": ")
(format t "~a" (evenodd (+ n 1))) (terpri))

Output:

1: odd
 2: even
 3: odd
 4: even
 5: odd
 6: even
 7: odd
 8: even
 9: odd
10: even

Component Pascal

BlackBox Component Builder

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;

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

Crystal

#Using bitwise shift
  def isEven_bShift(n)
    n == ((n >> 1) << 1)
  end
  def isOdd_bShift(n)
    n != ((n >> 1) << 1)
  end
#Using modulo operator
  def isEven_mod(n)
    (n % 2) == 0
  end
  def isOdd_mod(n)
    (n % 2) != 0
  end
# Using bitwise "and"
  def isEven_bAnd(n)
    (n & 1) ==  0
  end
  def isOdd_bAnd(n)
    (n & 1) != 0
  end

puts isEven_bShift(7)
puts isOdd_bShift(7)

puts isEven_mod(12)
puts isOdd_mod(12)

puts isEven_bAnd(21)
puts isOdd_bAnd(21)
Output:
false
true
true
false
false
true

D

void main() {
    import std.stdio, std.bigint;

    foreach (immutable i; -5 .. 6)
        writeln(i, " ", i & 1, " ", i % 2, " ", i.BigInt % 2);
}
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

Dart

void main() {
  for (var i = 1; i <= 10; i++) {
    if (i % 2 != 0) {
      print("$i is odd");
    } else {
      print("$i is even");
    }
  }
}

dc

This macro expects an integer on the stack, pops it, and pushes 1 if it is odd, or 0 if it is even (independently from the precision currently set).

[K Sk 0 k 2 % Lk k]

DCL

$! in DCL, for integers, the least significant bit determines the logical value, where 1 is true and 0 is false
$
$ i = -5
$ loop1:
$  if i then $ write sys$output i, " is odd"
$  if .not. i then $ write sys$output i, " is even"
$  i = i + 1
$  if i .le. 6 then $ goto loop1
Output:
$ @even_odd
-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
6 is even

Delphi

program EvenOdd;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

procedure IsOdd(aValue: Integer);
var
  Odd: Boolean;
begin
  Odd :=  aValue and 1 <> 0;
  Write(Format('%d is ', [aValue]));
  if Odd then
    Writeln('odd')
  else
    Writeln('even');
end;

var
  i: Integer;
begin
  for i := -5 to 10 do
    IsOdd(i);

  Readln;
end.
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
6 is even
7 is odd
8 is even
9 is odd
10 is even

Déjà Vu

even n:
    = 0 % n 2

odd:
    not even

!. odd 0
!. even 0
!. odd 7
!. even 7
Output:
false
true
true
false

Diego

use_namespace(rosettacode)_me();

funct(isEven)_arg(i)_ret()_calc(i%2)_equals(0);

reset_namespace[];

DWScript

Predicate:

var isOdd := Odd(i);

Bitwise and:

var isOdd := (i and 1)<>0;

Modulo:

var isOdd := (i mod 2)=1;

EasyLang

a = 13
if a mod 2 = 0
   print a & " is even"
else
   print a & " is odd"
.

EDSAC order code

This implementation uses the C (logical AND multiplier register with memory) order. It will cause the machine to print an E if the number stored at address θ+15 is even, or an O if it is odd. As an example, we shall test the number 37 (P18D in EDSAC encoding).

[ Even or odd
  ===========

  A program for the EDSAC

  Determines whether the number stored at
  address 15@ is even or odd, and prints
  'E' or 'O' accordingly

  Works with Initial Orders 2 ]

       T56K   [ load point ]
       GK     [ base address ]

       O11@   [ print letter shift ]
       T10@   [ clear accumulator ]
       H15@   [ multiplier := n ]
       C12@   [ acc +:= mult AND 1 ]
       S12@   [ acc -:= 1 ]
       G8@    [ branch on negative ]
       O14@   [ print 'O' ]
       ZF     [ halt ]
[ 8 ]  O13@   [ print 'E' ]
       ZF     [ halt ]

[ 10 ] P0F    [ used to clear acc ]
[ 11 ] *F     [ letter shift character ]
[ 12 ] P0D    [ const: 1 ]
[ 13 ] EF     [ character 'E' ]
[ 14 ] OF     [ character 'O' ]
[ 15 ] P18D   [ number to test: 37 ]

       EZPF   [ branch to load point ]
Output:
O

Eiffel

--bit testing
if i.bit_and (1) = 0 then
	-- i is even
end

--built-in bit testing (uses bit_and)
if i.bit_test (0) then
	-- i is odd
end

--integer remainder (modulo)
if i \\ 2 = 0 then
	-- i is even
end

Elixir

defmodule RC do
  import Integer

  def even_or_odd(n) when is_even(n), do: "#{n} is even"
  def even_or_odd(n)                , do: "#{n} is odd"
      # In second "def", the guard clauses of "is_odd(n)" is unnecessary.

  # Another definition way
  def even_or_odd2(n) do
    if is_even(n), do: "#{n} is even", else: "#{n} is odd"
  end
end

Enum.each(-2..3, fn n -> IO.puts RC.even_or_odd(n) end)
Output:
-2 is even
-1 is odd
0 is even
1 is odd
2 is even
3 is odd

Other ways to test even-ness:

rem(n,2) == 0

Emacs Lisp

(require 'cl-lib)

(defun even-or-odd-p (n)
  (if (cl-evenp n) 'even 'odd))

(defun even-or-odd-p (n)
 (if (zerop (% n 2)) 'even 'odd))

(message "%d is %s" 3 (even-or-oddp 3))
(message "%d is %s" 2 (even-or-oddp 2))
Output:
3 is odd
2 is even



EMal

List evenCheckers = fun[
  logic by int i do return i % 2 == 0 end,
  logic by int i do return i & 1 == 0 end]
List oddCheckers = fun[
  logic by int i do return i % 2 != 0 end,
  logic by int i do return i & 1 == 1 end]
writeLine("integer".padStart(10, " ") + "|is_even" + "|is_odd |")  
writeLine("----------+-------+-------+")
for each int i in range(-5, 6).append(3141592653)
  write((text!i).padStart(10, " ") + "| ")
  for each fun isEven in evenCheckers
    write(isEven(i) + "  ")
  end
  write("| ")
  for each fun isOdd in oddCheckers
    write(isOdd(i) + "  ")
  end
  writeLine("|")
end
writeLine("----------+-------+-------+")
Output:
   integer|is_even|is_odd |
----------+-------+-------+
        -5| ⊥  ⊥  | ⊤  ⊤  |
        -4| ⊤  ⊤  | ⊥  ⊥  |
        -3| ⊥  ⊥  | ⊤  ⊤  |
        -2| ⊤  ⊤  | ⊥  ⊥  |
        -1| ⊥  ⊥  | ⊤  ⊤  |
         0| ⊤  ⊤  | ⊥  ⊥  |
         1| ⊥  ⊥  | ⊤  ⊤  |
         2| ⊤  ⊤  | ⊥  ⊥  |
         3| ⊥  ⊥  | ⊤  ⊤  |
         4| ⊤  ⊤  | ⊥  ⊥  |
         5| ⊥  ⊥  | ⊤  ⊤  |
3141592653| ⊥  ⊥  | ⊤  ⊤  |
----------+-------+-------+

Erlang

Using Division by 2 Method

%% 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.

Using the least-significant bit method

 %% 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.

ERRE

PROGRAM ODD_EVEN

! works for -2^15 <= n% < 2^15

FUNCTION ISODD%(N%)
      ISODD%=(N% AND 1)<>0
END FUNCTION

! works for -2^38 <= n# <= 2^38
FUNCTION ISODD#(N#)
      ISODD#=N#<>2*INT(N#/2)
END FUNCTION

BEGIN
  IF ISODD%(14) THEN PRINT("14 is odd") ELSE PRINT("14 is even") END IF
  IF ISODD%(15) THEN PRINT("15 is odd") ELSE PRINT("15 is even") END IF
  IF ISODD#(9876543210) THEN PRINT("9876543210 is odd") ELSE PRINT("9876543210 is even") END IF
  IF ISODD#(9876543211) THEN PRINT("9876543211 is odd") ELSE PRINT("9876543211 is even") END IF
END PROGRAM
Output:
14 is even
15 is odd
9876543210 is even
9876543211 is odd

Euphoria

Using standard function

include std/math.e

for i = 1 to 10 do
        ? {i, is_even(i)}
end for
Output:
{1,0}
{2,1}
{3,0}
{4,1}
{5,0}
{6,1}
{7,0}
{8,1}
{9,0}
{10,1}

Excel

Use the MOD function

=MOD(33;2)
=MOD(18;2)
Output:
1
0

Use the ISEVEN function, returns TRUE or FALSE

=ISEVEN(33)
=ISEVEN(18)
Output:
FALSE
TRUE

Use the ISODD function, returns TRUE or FALSE

=ISODD(33)
=ISODD(18)
Output:
TRUE
FALSE

F#

Bitwise and:

let isEven x =
  x &&& 1 = 0

Modulo:

let isEven x =
  x % 2 = 0

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.

<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 ^

The actual computation is the 2%0= part. The rest is either user interface or parsing input.

Forth

: odd?  ( n -- ? ) 1 and ;
: even? ( n -- ? ) odd? 0= ;

\ Every value not equal to zero is considered true. Only zero is considered false.

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.

!-*- 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

Frink

isEven[x is isInteger] := getBit[x,0] == 0
isOdd[x is isInteger] := getBit[x,0] == 1

Futhark

This example is incorrect. Please fix the code and remove this message.

Details: Futhark's syntax has changed, so this example will not compile

fun main(x: int): bool = (x & 1) == 0


FutureBasic

local fn OddOrEven( i as NSInteger ) as CFStringRef
  CFStringRef result
  if ( i mod 2 ) == 0 then result = @"Even" else result = @"Odd"
end fn = result

NSUInteger i

for i = 1 to 10
  printf @"%d is %@", i, fn OddOrEven( i )
next

HandleEvents


Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solutions

Case 1. Intrinsic expressions:

Case 2. Using the Divides and DoesNotDivide expressions:

Case 3. Using modular congruences

Case 4. Using bitwise operations

Case 5. Using IsRational

GAP

IsEvenInt(n);
IsOddInt(n);

Genie

Using bitwise AND of the zero-bit.

[indent = 4]
/*
   Even or odd, in Genie
   valac even_or_odd.gs
*/

def parity(n:int):bool
    return ((n & 1) == 0)

def show_parity(n:int):void
    print "%d is %s", n, parity(n) ? "even" : "odd"

init
    show_parity(0)
    show_parity(1)
    show_parity(2)
    show_parity(-2)
    show_parity(-1)
Output:
prompt$ valac even_or_odd.gs
prompt$ ./even_or_odd
0 is even
1 is odd
2 is even
-2 is even
-1 is odd

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")
    }
}
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:

def isOdd = { int i -> (i & 1) as boolean }
def isEven = {int i -> ! isOdd(i) }

Test:

1.step(20, 2) { assert isOdd(it) }

50.step(-50, -2) { assert isEven(it) }

Haskell

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

Prelude> even 5
False
Prelude> even 42
True
Prelude> odd 5
True
Prelude> odd 42
False

Where even is derived from rem, and odd is derived from even:

import Prelude hiding (even, odd)

even, odd
  :: (Integral a)
  => a -> Bool
even = (0 ==) . (`rem` 2)

odd = not . even

main :: IO ()
main = print (even <$> [0 .. 9])
Output:
[True,False,True,False,True,False,True,False,True,False]

Hoon

|=  n=@ud
?:  =((mod n 2) 0)
  "even"
"odd"

Icon and Unicon

One way is to check the remainder:

procedure isEven(n)
    return n%2 = 0
end

Insitux

Exactly the same as Clojure, these are built-in predicates.

(if (even? some-var) (do-even-stuff))
(if (odd? some-var) (do-odd-stuff))

J

Modulo:

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

Remainder:

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

Last bit in bit representation:

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

Bitwise and:

   1 (17 b.) 2 3 5 7
0 1 1 1

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

Jakt

fn is_even<T>(anon n: T) -> bool => 0 == (n & 1)

fn is_odd<T>(anon n: T) -> bool => 0 != (n & 1)

fn main() {
    for i in 0..11 {
        println("{} {} {}", i, is_even(i), is_odd(i))
    }
}

Java

Bitwise and:

public static boolean isEven(int i){
    return (i & 1) == 0;
}

Modulo:

public static boolean isEven(int i){
    return (i % 2) == 0;
}

Arbitrary precision bitwise:

public static boolean isEven(BigInteger i){
    return i.and(BigInteger.ONE).equals(BigInteger.ZERO);
}

Arbitrary precision bit test (even works for negative numbers because of the way BigInteger represents the bits of numbers):

public static boolean isEven(BigInteger i){
    return !i.testBit(0);
}

Arbitrary precision modulo:

public static boolean isEven(BigInteger i){
    return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);
}

JavaScript

ES5

Bitwise:

function isEven( i ) {
  return (i & 1) === 0;
}

Modulo:

function isEven( i ) {
  return i % 2 === 0;
}

// Alternative
function isEven( i ) {
  return !(i % 2);
}

ES6

Lambda:

// EMCAScript 6
const isEven = x => !(x % 2)

or, avoiding type coercion:

(() => {
    'use strict';

    // even : Integral a => a -> Bool
    const even = x => (x % 2) === 0;

    // odd : Integral a => a -> Bool
    const odd = x => !even(x);


    // TEST ----------------------------------------
    // range :: Int -> Int -> [Int]
    const range = (m, n) =>
        Array.from({
            length: Math.floor(n - m) + 1
        }, (_, i) => m + i);

    // show :: a -> String
    const show = JSON.stringify;

    // xs :: [Int]
    const xs = range(-6, 6);

    return show([xs.filter(even), xs.filter(odd)]);
})();
Output:
[[-6,-4,-2,0,2,4,6],[-5,-3,-1,1,3,5]]

Joy

DEFINE
  even == 2 rem null;
  odd == even not.

jq

In practice, to test whether an integer, i, is even or odd in jq, one would typically use: i % 2

For example, if it were necessary to have a strictly boolean function that would test if its input is an even integer, one could define:

def is_even: type == "number" and floor == 0 and . % 2 == 0;

The check that the floor is 0 is necessary as % is defined on floating point numbers.

"is_odd" could be similarly defined:

def is_odd: type == "number" and floor == 0 and . % 2 == 1;

Jsish

Using bitwise and of low bit.

#!/usr/bin/env jsish
/* Even or Odd, in Jsish */
function isEven(n:number):boolean { return (n & 1) === 0; }

provide('isEven', 1);

if (Interp.conf('unitTest')) {
;    isEven(0);
;    isEven(1);
;    isEven(2);
;    isEven(-13);
}

/*
=!EXPECTSTART!=
isEven(0) ==> true
isEven(1) ==> false
isEven(2) ==> true
isEven(-13) ==> false
=!EXPECTEND!=
*/
Output:
$ jsish --U isEven.jsi
isEven(0) ==> true
isEven(1) ==> false
isEven(2) ==> true
isEven(-13) ==> false

Julia

Built-in functions:

iseven(i), isodd(i)

K

The following implementation uses the modulo of division by 2

oddp: {:[x!2;1;0]} /Returns 1 if arg. is odd
evenp: {~oddp[x]}  /Returns 1 if arg. is even

Examples:
   oddp 32
0
   evenp 32
1


Klingphix

( -5 5 ) [
    dup print " " print 2 mod ( ["Odd"] ["Even"] ) if print nl
] for

" " input
Output:
-5 Odd
-4 Even
-3 Odd
-2 Even
-1 Odd
0 Even
1 Odd
2 Even
3 Odd
4 Even
5 Odd

Kotlin

// version 1.0.5-2

fun main(args: Array<String>) {
    while (true) {
        print("Enter an integer or 0 to finish : ")
        val n = readLine()!!.toInt()
        when {
            n == 0     -> return
            n % 2 == 0 -> println("Your number is even")
            else       -> println("Your number is odd")
        }
    }
}

Lambdatalk

{def is_odd {lambda {:i} {= {% :i 2} 1}}}
-> is_odd

{def is_even {lambda {:i} {= {% :i 2} 0}}}
-> is_even

{is_odd 2}
-> false

{is_even 2}
-> true

L++

(defn bool isEven (int x) (return (% x 2)))

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

: even?  2 % not ;
: odd?  2 % ;
1 even? .   # 0
1 odd? .    # 1

Lasso

define isoddoreven(i::integer) => {
	#i % 2 ? return 'odd'
	return 'even'
}
isoddoreven(12)

LC3 Assembly

Prints EVEN if the number stored in NUM is even, otherwise ODD.

      .ORIG      0x3000

      LD         R0,NUM
      AND        R1,R0,1
      BRZ        EVEN

      LEA        R0,ODD
      BRNZP      DISP

EVEN  LEA        R0,EVN

DISP  PUTS

      HALT

NUM   .FILL      0x1C

EVN   .STRINGZ   "EVEN\n"
ODD   .STRINGZ   "ODD\n"

      .END

Lingo

on even (n)
  return n mod 2 = 0
end

on odd (n)
  return n mode 2 <> 0
end

Little Man Computer

Runs in Peter Higginson's simulator, to allow comments. Does not use his other extensions to the language.

LMC has no division instruction. To divide by 2 we could use repeated subtraction:

// Input number; output its residue mod 2
       INP        // read input into acc
       BRZ write  // input = 0 is special case
loop   SUB k2     // keep subtracting 2 from acc
       BRZ write  // if acc = 0, input is even
       BRP loop   // if acc > 0, loop back
                  // (BRP branches if acc >= 0, but we've dealt with acc = 0)
       LDA k1     // if acc < 0, input is odd
write  OUT        // output 0 or 1
       HLT        // halt
k1     DAT 1      // constant 1
k2     DAT 2      // constant 2
// end

The above program might need 500 subtractions before it found the result. To speed things up we could use something along the following lines.

// Input number; output its residue mod 2
         INP          // read input into accumulator
loop1    STA save_acc // save accumulator (see note below)
         SUB k128     // keep subtracting 128 until acc < 0
         BRP loop1
         LDA save_acc // save_acc holds a number in range 0..127
loop2    STA save_acc
         SUB k16      // keep subtracting 16 until acc < 0
         BRP loop2
         LDA save_acc // save_acc holds a number in range 0..15
loop3    STA save_acc
         SUB k2       // keep subtracting 2 until acc < 0
         BRP loop3
         LDA save_acc // save_acc holds 0 or 1, the result
write    OUT          // output result
         HLT
k2       DAT 2
k16      DAT 16
k128     DAT 128
save_acc DAT
// end

Note: LMC, in its original form, does not support negative numbers. If the accumulator contains a number X, and a number Y > X is subtracted, then the negative flag is set and the value in the accumulator becomes undefined. So we can't assume that adding Y back to the accumulator will restore the value of X. If we want to use X again, we need to save it in RAM before doing the subtraction.


LiveCode

function odd n
    return (n bitand 1) = 1
end odd

function notEven n
    return (n mod 2) = 1
end notEven

LLVM

; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)

$"EVEN_STR" = comdat any
$"ODD_STR" = comdat any

@"EVEN_STR" = linkonce_odr unnamed_addr constant [12 x i8] c"%d is even\0A\00", comdat, align 1
@"ODD_STR" = linkonce_odr unnamed_addr constant [11 x i8] c"%d is odd\0A\00", comdat, align 1

; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4          ;-- allocate i
  store i32 0, i32* %1, align 4     ;-- store 0 in i
  br label %loop

loop:
  %2 = load i32, i32* %1, align 4   ;-- load i
  %3 = icmp ult i32 %2, 4           ;-- i < 4
  br i1 %3, label %loop_body, label %exit

loop_body:
  %4 = load i32, i32* %1, align 4   ;-- load i
  %5 = and i32 %4, 1                ;-- i & 1
  %6 = icmp eq i32 %5, 0            ;-- (i & 1) == 0
  br i1 %6, label %even_branch, label %odd_branch

even_branch:
  %7 = load i32, i32* %1, align 4   ;-- load i
  %8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"EVEN_STR", i32 0, i32 0), i32 %7)
  br label %loop_increment

odd_branch:
  %9 = load i32, i32* %1, align 4   ;-- load i
  %10 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"ODD_STR", i32 0, i32 0), i32 %9)
  br label %loop_increment

loop_increment:
  %11 = load i32, i32* %1, align 4  ;-- load i
  %12 = add i32 %11, 1              ;-- increment i
  store i32 %12, i32* %1, align 4   ;-- store i
  br label %loop

exit:
  ret i32 0
}

attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
Output:
0 is even
1 is odd
2 is even
3 is odd

to even? :num
    output equal? 0 modulo :num 2
end

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.
Output:
| ?- 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

LOLCODE

HAI 1.4
I HAS A integer
GIMMEH integer
I HAS A remainder
remainder R MOD OF integer AN 2
BOTH SAEM remainder AN 1, O RLY?
YA RLY
VISIBLE "The integer is odd."
NO WAI
VISIBLE "The integer is even."
OIC 
KTHXBYE

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

M2000 Interpreter

Binary.Add take any numeric type, but value from newer versions can trait as unsigned with range of 0 to 0xFFFFFFFF (so if the number is out of this range, a cut made).

Print binary.and(0xFFFFFFF+10, 0XF)=9 // 0xFFFFFFFF is type Currency and return 4294967295, number 10 is type double so the final number for addition is type double.

Print binary.and(0xFFFFFFF&+10, 0XF)=9 // 0xFFFFFFFF& is type long and return -1, number 10 is type double so the final number for addition is type double.

Print binary.and(0x7FFFFFFF&*16&+10&, 0xF)=15 // 0x7FFFFFFF&*16& cant fit in long so it is type of double 34359738352 (this performed automatic). But if we give this Long A=0x7FFFFFFF&*16& we get an overflow error, because A is a Long, and 34359738352 can't fit.

So Mod if a perfect choice, using it with Decimals (character @ indicate a Decimal type or literal). Variable a take the type of input. There is no reason here to write it as def Odd(a as decimal)= binary.and(Abs(a), 1)=1

Def used to define variables (an error occur if same variable exist), or to define one line local functions. If a function exist then replace code. This is the same for modules/functions, a newer definition alter an old definition with same name, in current module if they are local, or global if they defined as global, like this:

Function Global F(x) { code block here}.

A function F(x) {} is same as

Function F {
      Read x
      code here
}

The same hold for Def Odd(a)=binary.and(Abs(a), 1)=1 Interpreter execute this:

Function Odd {
      Read a
      =binary.and(Abs(a), 1)=1
}

So here is the task. Show an overflow from a decimal, then change function.

Module CheckOdd {
      Def Odd(a)= binary.and(Abs(a), 1)=1
      Print Odd(-5), Odd(6), Odd(11)
      Print Odd(21212121212122122122121@)
      def Odd(a)= Int(Abs(a)) mod 2 =1
      Print Odd(21212121212122122122121@)
      Print Odd(-5), Odd(6), Odd(11)
}
CheckOdd

M4

define(`even', `ifelse(eval(`$1'%2),0,True,False)')
define(`odd',  `ifelse(eval(`$1'%2),0,False,True)')

even(13)
even(8)

odd(5)
odd(0)

Maple

EvenOrOdd := proc( x::integer )
   if x mod 2 = 0 then
      print("Even"):
   else
      print("Odd"):
   end if:
end proc:
EvenOrOdd(9);
"Odd"

Mathematica / Wolfram Language

EvenQ[8]

MATLAB / Octave

Bitwise And:

   isOdd  =  logical(bitand(N,1));
   isEven = ~logical(bitand(N,1));

Remainder of division by two:

   isOdd  =  logical(rem(N,2));
   isEven = ~logical(rem(N,2));

Modulo: 2

   isOdd  =  logical(mod(N,2));
   isEven = ~logical(mod(N,2));

Maxima

evenp(n);
oddp(n);

MAXScript

-- MAXScript : Even or Odd : N.H. 2019
-- Open the MAXScript Listener for input and output
userInt = getKBValue prompt:"Enter an integer and i will tell you if its Even or Odd : "
if classOf userInt != Integer then print "The value you enter must be an integer"
else if (Mod userInt 2) == 0 Then Print "Your number is even"
else Print "Your number is odd"

Mercury

Mercury's 'int' module provides tests for even/odd, along with all the operators that would be otherwise used to implement them.

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.

min

Works with: min version 0.19.3
3 even?
4 even?
5 odd?
get-stack print
Output:
(false true true)

MiniScript

for i in range(-4, 4)
    if i % 2 == 0 then print i + " is even" else print i + " is odd"
end for
Output:
-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

MIPS Assembly

This uses bitwise AND

.data
	even_str: .asciiz "Even"
	odd_str: .asciiz "Odd"

.text
	#set syscall to get integer from user
	li $v0,5
	syscall

	#perform bitwise AND and store in $a0
	and $a0,$v0,1

	#set syscall to print dytomh
	li $v0,4

	#jump to odd if the result of the AND operation
	beq $a0,1,odd
even:
	#load even_str message, and print
	la $a0,even_str
	syscall

	#exit program
	li $v0,10
	syscall

odd:
	#load odd_str message, and print
	la $a0,odd_str
	syscall

	#exit program
	li $v0,10
	syscall

МК-61/52

/	2	{x}	ЗН

Result: "0" - number is even; "1" - number is odd.

ML

fun even( x: int ) = (x mod 2 = 0);
fun odd( x: int ) = (x mod 2 = 1);

mLite

fun odd
		(x rem 2 = 1) = true
	| 	_ 	      = false
;

fun even
		(x rem 2 = 0) = true
	| 	_ 	      = false
;

Modula-2

MODULE EvenOrOdd;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;

VAR
    buf : ARRAY[0..63] OF CHAR;
    i : INTEGER;
BEGIN
    FOR i:=-5 TO 5 DO
        FormatString("%i is even: %b\n", buf, i, i MOD 2 = 0);
        WriteString(buf)
    END;

    ReadChar
END EvenOrOdd.

Nanoquery

def isEven(n)
        if ((n % 2) = 1)
                return false
        else
                return true
        end
end

for i in range(1, 10)
        print i
        if isEven(i)
                println " is even."
        else
                println " is odd."
        end
end
Output:
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.

Neko

var number = 6;

if(number % 2 == 0) {
	$print("Even");
} else {
	$print("Odd");
}
Output:
Even

NESL

NESL provides evenp and oddp functions, but they wouldn't be hard to reimplement.

function even(n) = mod(n, 2) == 0;

% test the function by applying it to the first ten positive integers: %
{even(n) : n in [1:11]};
Output:
it = [F, T, F, T, F, T, F, T, F, T] : [bool]

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)
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

Never

func isOdd(n : int) -> int {
    n % 2 == 1
}

func isEven(n : int) -> int {
    n % 2 == 0
}

NewLISP

(odd? 1)
(even? 2)

Nim

# Least signficant bit:
proc isOdd(i: int): bool = (i and 1) != 0
proc isEven(i: int): bool = (i and 1) == 0

# Modulo:
proc isOdd2(i: int): bool = (i mod 2) != 0
proc isEven2(i: int): bool = (i mod 2) == 0

# Bit Shifting:
proc isOdd3(n: int): bool = n != ((n shr 1) shl 1)
proc isEven3(n: int): bool = n == ((n shr 1) shl 1)

echo isEven(1)
echo isOdd2(5)

Oberon-2

Works with: oo2c
MODULE EvenOrOdd;
IMPORT
  S := SYSTEM,
  Out;
VAR
  x: INTEGER;
  s: SET;

BEGIN
  x := 10;Out.Int(x,0);
  IF ODD(x) THEN Out.String(" odd") ELSE Out.String(" even") END;
  Out.Ln;

  x := 11;s := S.VAL(SET,LONG(x));Out.Int(x,0);
  IF 0 IN s THEN Out.String(" odd") ELSE Out.String(" even") END;
  Out.Ln;

  x := 12;Out.Int(x,0);
  IF x MOD 2 # 0 THEN Out.String(" odd") ELSE Out.String(" even") END;
  Out.Ln
END EvenOrOdd.
Output:
10 even
11 odd
12 even

Objeck

a := Console->ReadString()->ToInt();
if(a % 2 = 0) {
  "even"->PrintLine();
}
else {
  "odd"->PrintLine();
};

OCaml

Modulo:

let is_even d =
  (d mod 2) = 0

let is_odd d =
  (d mod 2) <> 0

Bitwise and:

let is_even d =
  (d land 1) = 0

let is_odd d =
  (d land 1) <> 0

An instructive view on functional programming and recursion:

(* hmm, only valid for N >= 0 *)
let rec myeven = function
  | 0 -> true
  | 1 -> false
  | n -> myeven (n - 2)

(* and here we have the not function in if form *)
let myodd n = if myeven n then false else true

Oforth

12 isEven
12 isOdd

Ol

Actually, 'even?' and 'odd?' functions are built-in. But,

; 1. Check the least significant bit.
(define (even? i)
   (if (eq? (band i 1) 0) #t #f))
(define (odd? i)
   (if (eq? (band i 1) 1) #t #f))

(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd
(print (if (odd? 12345678987654321) "odd" "even"))  ; ==> odd
(print (if (even? 1234567898765432) "even" "odd"))  ; ==> even
(print (if (odd? 1234567898765432) "odd" "even"))   ; ==> even

; 2. Divide i by 2. The remainder equals 0 iff i is even.
(define (even? i)
   (if (eq? (remainder i 2) 0) #t #f))
(define (odd? i)
   (if (eq? (remainder i 2) 1) #t #f))

(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd
(print (if (odd? 12345678987654321) "odd" "even"))  ; ==> odd
(print (if (even? 1234567898765432) "even" "odd"))  ; ==> even
(print (if (odd? 1234567898765432) "odd" "even"))   ; ==> even

; 3. Use modular congruences. Same as 2.
(define (even? i)
   (if (eq? (mod i 2) 0) #t #f))
(define (odd? i)
   (if (eq? (mod i 2) 1) #t #f))

(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd
(print (if (odd? 12345678987654321) "odd" "even"))  ; ==> odd
(print (if (even? 1234567898765432) "even" "odd"))  ; ==> even
(print (if (odd? 1234567898765432) "odd" "even"))   ; ==> even

OOC

// Using the modulo operator
even: func (n: Int) -> Bool {
  (n % 2) == 0
}

// Using bitwise and
odd: func (n: Int) -> Bool {
  (n & 1) == 1
}

PARI/GP

GP does not have a built-in predicate for testing parity, but it's easy to code:

odd(n)=n%2;

Alternately:

odd(n)=bitand(n,1);

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:

isOdd := odd(someIntegerNumber);

bitwise and:

function isOdd(Number: integer): boolean
begin
  isOdd := boolean(Number and 1)
end;

Dividing and multiplying by 2 and test on equality:

function isEven(Number: integer): boolean
begin
  isEven := (Number = ((Number div 2) * 2))
end;

Using built-in modulo

function isOdd(Number: integer): boolean
begin
  isOdd := boolean(Number mod 2)
end;

Perl

for(0..10){
    print "$_ is ", qw(even odd)[$_ % 2],"\n";
}

or

print 6 % 2  ? 'odd' : 'even';   # prints even

Phix

There are builtin routines odd() and even() which return true/false - note however they will round non-integer arguments to the nearest whole number, which might be confusing. The mpz_odd() and mpz_even() are similar, but without any way to pass them fractions. In fact odd() invokes and_bits(i,1)=1 and even() invokes and_bits(i,1)=0, so no difference there, and "i&&1" is just shorthand for and_bits(i,1). Lastly remainder(i,2) can also validly be used, however "true" for odd numbers is actually 1 for positive odd integers and -1 for negative odd integers, plus fractions are preserved, so "remainder(i,2)==0" is perhaps for some uses a more flexible and accurate "even"/"not even" test.

with javascript_semantics
include mpfr.e
mpz z = mpz_init()
printf(1," i    odd  even  &&1  rmdr(2)\n")
for i=-5 to 5 do
    mpz_set_si(z,i)
    printf(1,"%2d: %5t %5t %3d %5d\n",{i,odd(i),even(i),i&&1,remainder(i,2)})
end for
Output:
 i    odd  even  &&1  rmdr(2)
-5:  true false   1    -1
-4: false  true   0     0
-3:  true false   1    -1
-2: false  true   0     0
-1:  true false   1    -1
 0: false  true   0     0
 1:  true false   1     1
 2: false  true   0     0
 3:  true false   1     1
 4: false  true   0     0
 5:  true false   1     1

Phixmonti

-5 5 2 tolist for
    dup print " " print 2 mod if "Odd" else "Even" endif print nl
endfor

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';
Output:
even
odd
odd
even

Picat

Works with: Picat
% Bitwise and
is_even_bitwise(I) = cond(I /\ 1 == 0, true, false).

% Modulo
is_even_mod(I) = cond(I mod 2 == 0, true, false).

% Remainder
is_even_rem(I) = cond(I rem 2 == 0, true, false).

yes_or_no(B) = YN =>
    B = true, YN = "Yes";
    B = false, YN = "No".

main :-
    foreach (I in 2..3)
        printf("%d is even? %s\n", I, yes_or_no(is_even_bitwise(I))),
        printf("%d is even? %s\n", I, yes_or_no(is_even_mod(I))),
        printf("%d is even? %s\n", I, yes_or_no(is_even_rem(I)))
    end.
Output:
2 is even? Yes
2 is even? Yes
2 is even? Yes
3 is even? No
3 is even? No
3 is even? No

Note: Picat has even/1 and odd/1 as built-ins predicates.

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.

: (bit? 1 3)
-> 1  # Odd

: (bit? 1 4)
-> NIL  # Even

Pike

> int i = 73;
> (i&1);
Result: 1
> i%2;
Result: 1

PL/I

i = iand(i,1)

The result is 1 when i is odd, and 0 when i is even.

PL/M

In PL/M, even numbers are falsy and odd numbers are truthy, so no explicit test is needed at all.

100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2, CH); END PUT$CHAR;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;

DECLARE I BYTE;
DO I='0' TO '9';
    CALL PUT$CHAR(I);
    CALL PRINT(.' IS $');
    IF I THEN
        CALL PRINT(.'ODD$');
    ELSE
        CALL PRINT(.'EVEN$');
    CALL PRINT(.(13,10,'$'));
END;

CALL EXIT;
EOF
Output:
0 IS EVEN
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

Plain English

The noodle comes with even and odd deciders.

To run:
Start up.
If 56 is even, write "56 is even!" to the console.
If 4 is odd, write "4 is odd!" to the console.
Wait for the escape key.
Shut down.
Output:
56 is even!

PowerShell

Works with: PowerShell version 2

Predicate

A predicate can be used with BigInteger objects. Even/odd predicates to not exist for basic value types. Type accelerator [bigint] can be used in place of [System.Numerics.BigInteger].

$IsOdd  = -not ( [bigint]$N ).IsEven
$IsEven =      ( [bigint]$N ).IsEven

Least significant digit

$IsOdd  = [boolean]( $N -band 1 )
$IsEven = [boolean]( $N -band 0 )

Remainder

Despite being known as a modulus operator, the % operator in PowerShell actually returns a remainder. As such, when testing negative numbers it returns the true modulus result minus M. In this specific case, it returns -1 for odd negative numbers. Thus we test for not zero for odd numbers.

$IsOdd  = $N % 2 -ne 0
$IsEven = $N % 2 -eq 0

Processing

boolean isEven(int i){
  return i%2 == 0;
}

boolean isOdd(int i){
  return i%2 == 1;
}

Prolog

Prolog does not provide special even or odd predicates as one can simply write "0 is N mod 2" to test whether the integer N is even. To illustrate, here is a predicate that can be used both to test whether an integer is even and to generate the non-negative even numbers:

  even(N) :-
     (between(0, inf, N); integer(N) ),
     0 is N mod 2.

Least Significant Bit

If N is a positive integer, then lsb(N) is the offset of its least significant bit, so we could write:

  odd(N) :- N = 0 -> false; 0 is lsb(abs(N)).

Python

Python: Using the least-significant bit method

>>> 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)]
>>>

Python: Using modular congruences

>> def is_even(i):
        return (i % 2) == 0

>>> is_even(1)
False
>>> is_even(2)
True
>>>

Quackery

[ 1 & ]     is odd  ( n --> b )

[ odd not ] is even ( n --> b )
Output:

In the Quackery shell (REPL):

/O> 10 even
... 10 odd
... 11 even
... 11 odd
...

Stack: 1 0 0 1

Quackery: With Anonymous Mutual Recursion

Adapted from the example code at wp:Mutual recursion#Basic examples, with the additional observation that the parity of a negative number is the same as the parity of its absolute value.

See also Mutual recursion#Quackery and Anonymous recursion#Quackery.

  [ abs

    ' [ dup 0 = iff
         [ 2drop true ] done
         1 - this swap rot do ] ( x n --> b )

    ' [ dup 0 = iff
         [ 2drop false ] done
         1 - this swap rot do ] ( x n --> b )

     unrot do ]                 is even ( n --> b )

  11 times
    [ i^ 5 - dup echo
      say " is "
     even iff [ $ "even" ]
     else [ $ "odd" ]
     echo$ say "." cr ]
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.

R

is.even <- function(x) !is.odd(x)

is.odd <- function(x) intToBits(x)[1] == 1
#or
is.odd <- function(x) x %% 2 == 1

Racket

With built in predicates:

(even? 6) ; -> true
(even? 5) ; -> false
(odd? 6) ; -> false
(odd? 5) ; -> true

With modular arithmetic:

(define (my-even? x)
  (= (modulo x 2) 0))

(define (my-odd? x)
  (= (modulo x 2) 1))

With mutually recursive functions:

(define (even-or-odd? i)
  (letrec ([even? (λ (n)
                    (if (= n 0)
                        'even
                        (odd? (sub1 n))))]
           [odd? (λ (n)
                   (if (= n 0)
                       'odd
                       (even? (sub1 n))))])
    (even? i)))

(even-or-odd? 100)  ; => 'even
(even-or-odd? 101)  ; => 'odd

Raku

(formerly Perl 6) Raku doesn't have a built-in for this, but with subsets it's easy to define a predicate for it.

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 )

Rascal

public bool isEven(int n) = (n % 2) == 0;
public bool isOdd(int n) = (n % 2) == 1;

Or with block quotes:

public bool isEven(int n){return (n % 2) == 0;}
public bool isOdd(int n){return (n % 2) == 1;}

RATFOR

program evenodd

integer a

write(*,101,ADVANCE="NO")
read(*,102)a

if (mod(a,2) .eq. 0) write(*,103)a
   else   write(*,104)a


101  format("Enter a number: ")
102  format(i7)
103  format(i7," Is Even.")
104  format(i7," Is Odd.")


end

Rapira

fun is_even(n)
  return (n /% 2) = 0
end

Red

Red [
    date: 2021-10-24
    red-version: 0.6.4
    description: "Test whether an integer is even or odd."
]

print even? 10 ;== true
print odd? 10 ;== false

ReScript

let is_even = d => mod(d, 2) == 0

let is_odd = d => mod(d, 2) != 0

REXX

Programming note:   division by   1   (one)   in REXX is a way to normalize a number:

  • by removing a superfluous leading   +   sign
  • by removing superfluous leading zeroes
  • by removing superfluous trailing zeroes
  • by removing a trailing decimal point
  • possible converting an exponentiated number
  • possible rounding the number to the current digits

Programming note:   the last method is the fastest method in REXX to determine oddness/evenness.
It requires a sparse stemmed array     !.     be defined in the program's prologue (or elsewhere).
This method gets its speed from   not   using any BIF and   not   performing any (remainder) division.

Some notes on programming styles:   If (execution) speed isn't an issue, then the 1st test method
shown would be the simplest   (in terms of coding the concisest/tightest/smallest code).   The other test
methods differ mostly in programming techniques, mostly depending on the REXX programmer's style.  
The last method shown is the fastest algorithm, albeit it might be a bit obtuse (without comments) to a
novice reader of the REXX language   (and it requires additional REXX statement baggage).

/*REXX program tests and displays if an integer is  even or odd  using different styles.*/
!.=0;   do j=0  by 2  to 8;   !.j=1;   end       /*assign  0,2,4,6,8  to a "true" value.*/
                                                 /* [↑]  assigns even digits to  "true".*/
numeric digits 1000                              /*handle most huge numbers from the CL.*/
parse arg x _ .                                  /*get an argument from the command line*/
if x==''               then call terr "no integer input (argument)."
if _\=='' | arg()\==1  then call terr "too many arguments: "          _  arg(2)
if \datatype(x, 'N')   then call terr "argument isn't numeric: "      x
if \datatype(x, 'W')   then call terr "argument isn't an integer: "   x
y=abs(x)/1                                       /*in case  X  is negative or malformed,*/
                                                 /* [↑]  remainder of neg # might be -1.*/
                                                 /*malformed #s: 007  9.0  4.8e1  .21e2 */
call tell 'remainder method (oddness)'
if y//2  then say  x  'is odd'
         else say  x  'is even'
                                                 /* [↑]  uses division to get remainder.*/

call tell 'rightmost digit using BIF (not evenness)'
_=right(y, 1)
if pos(_, 86420)==0  then say x 'is odd'
                     else say x 'is even'
                                                 /* [↑]  uses 2 BIF (built─in functions)*/

call tell 'rightmost digit using BIF (evenness)'
_=right(y, 1)
if pos(_, 86420)\==0  then say x 'is even'
                      else say x 'is odd'
                                                 /* [↑]  uses 2 BIF (built─in functions)*/

call tell 'even rightmost digit using array (evenness)'
_=right(y, 1)
if !._  then say x 'is even'
        else say x 'is odd'
                                                 /* [↑]  uses a BIF (built─in function).*/

call tell 'remainder of division via function invoke (evenness)'
if even(y)  then say x 'is even'
            else say x 'is odd'
                                                 /* [↑]  uses (even) function invocation*/

call tell 'remainder of division via function invoke (oddness)'
if odd(y)  then say x 'is odd'
           else say x 'is even'
                                                 /* [↑]  uses (odd)  function invocation*/

call tell 'rightmost digit using BIF (not oddness)'
_=right(y, 1)
if pos(_, 13579)==0  then say x 'is even'
                     else say x 'is odd'
                                                 /* [↑]  uses 2 BIF (built─in functions)*/

call tell 'rightmost (binary) bit (oddness)'
if right(x2b(d2x(y)), 1)  then say x 'is odd'
                          else say x 'is even'
                                                 /* [↑]  requires extra numeric digits. */

call tell 'parse statement using BIF (not oddness)'
parse var  y   ''  -1  _                         /*obtain last decimal digit of the Y #.*/
if pos(_, 02468)==0  then say x 'is odd'
                     else say x 'is even'
                                                 /* [↑]  uses a BIF (built─in function).*/

call tell 'parse statement using array (evenness)'
parse var  y   ''  -1  _                         /*obtain last decimal digit of the Y #.*/
if !._  then say  x  'is even'
        else say  x  'is odd'
                                                 /* [↑]  this is the fastest algorithm. */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
even:                     return \( arg(1)//2 )  /*returns "evenness" of arg, version 1.*/
even:                     return    arg(1)//2==0 /*   "         "      "  "      "    2.*/
even: parse arg '' -1 _;  return !._             /*   "         "      "  "      "    3.*/
                                                 /*last version shown is the fastest.   */
odd:                      return   arg(1)//2     /*returns  "oddness" of the argument.  */
tell: say;   say center('using the' arg(1), 79, "═");                    return
terr: say;   say '***error***';     say;    say arg(1);    say;          exit 13

output   when using the input of:   0

═════════════════════using the remainder method (oddness)══════════════════════
0 is even

══════════════using the rightmost digit using BIF (not evenness)═══════════════
0 is even

════════════════using the rightmost digit using BIF (evenness)═════════════════
0 is even

═════════════using the even rightmost digit using array (evenness)═════════════
0 is even

════════using the remainder of division via function invoke (evenness)═════════
0 is even

═════════using the remainder of division via function invoke (oddness)═════════
0 is even

═══════════════using the rightmost digit using BIF (not oddness)═══════════════
0 is even

══════════════════using the rightmost (binary) bit (oddness)═══════════════════
0 is even

═══════════════using the parse statement using BIF (not oddness)═══════════════
0 is even

═══════════════using the parse statement using array (evenness)════════════════
0 is even

output   when using the input of:   9876543210987654321098765432109876543210987654321

═════════════════════using the remainder method (oddness)══════════════════════
9876543210987654321098765432109876543210987654321 is odd

   (rest of the output was elided.)

output   when using the input of:   .6821e4

═════════════════════using the remainder method (oddness)══════════════════════
.8621e4 is odd

   (rest of the output was elided.)

output   when using the input of:   -9411

═════════════════════using the remainder method (oddness)══════════════════════
-9411 is odd

   (rest of the output was elided.)

Ring

size = 10
for i = 1 to size
    if i % 2 = 1 see "" + i + " is odd" + nl
    else see "" + i + " is even" + nl ok
next

RPL

To test oddity of real numbers (floating point numbers) :

≪ 2 MOD ≫ ‘ODD?’ STO

To test oddity of binary integers (unsigned integers) :

≪ #1 AND #1 ≠ ≫ ‘BODD?’ STO

To test oddity without caring of the data type :

≪ IF DUP TYPE THEN #1 AND #1 ≠ ELSE 2 MOD END ≫
Input:
47 ODD?
#Fh BODD?
Output:
2: 1
1: 1

Ruby

In Ruby, integers behave like objects, so they respond to methods like : 5.even? resulting to false

print "evens: "
p -5.upto(5).select(&:even?)
print "odds: "
p -5.upto(5).select(&:odd?)
Output:
evens: [-4, -2, 0, 2, 4]
odds: [-5, -3, -1, 1, 3, 5]

Other ways to test even-ness:

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?

Rust

Checking the least significant digit:

let is_odd = |x: i32| x & 1 == 1;
let is_even = |x: i32| x & 1 == 0;

Using modular congruences:

let is_odd = |x: i32| x % 2 != 0;
let is_even = |x: i32| x % 2 == 0;

Scala

def isEven( v:Int ) : Boolean = v % 2 == 0
def isOdd( v:Int ) : Boolean = v % 2 != 0

Accept any numeric type as an argument:

def isEven( v:Number ) : Boolean = v.longValue % 2 == 0
def isOdd( v:Number ) : Boolean = v.longValue % 2 != 0
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):

> (even? 5)
#f
> (even? 42)
#t
> (odd? 5)
#t
> (odd? 42)
#f

sed

s/[02468]$/& is even/
s/[13579]$/& is odd/
Output:
$ seq -18 7 17 | sed -f even_or_odd.sed                                                                                                                                                                                                                           
-18 is even
-11 is odd
-4 is even
3 is odd
10 is even
17 is odd

Seed7

Test whether an integer or bigInteger is odd:

odd(aNumber)

Test whether an integer or bigInteger is even:

not odd(aNumber)

SenseTalk

set num to random of 100 -- start with a random number from 1 to 100

// use the 'is a' operator to test the value
if num is an odd number then put num & " is odd"

// see if num is divisible by 2
if num is divisible by 2 then put num & " is even (is divisible by 2)"

// check to see if the remainder is 0 when dividing by 2
if num rem 2 is 0 then put num & " is even (zero remainder)"

SequenceL

even(x) := x mod 2 = 0;
odd(x) := x mod 2 = 1;
Output:
cmd:>even(1 ... 10)
[false,true,false,true,false,true,false,true,false,true]
cmd:>odd(1 ... 10)
[true,false,true,false,true,false,true,false,true,false]

SETL

SETL provides built-in even and odd functions. This short program illustrates their use.

xs := {1..10};
evens := {x in xs | even( x )};
odds := {x in xs | odd( x )};
print( evens );
print( odds );
Output:
{2 4 6 8 10}
{1 3 5 7 9}

Shen

Mutual Recursion:

(define even?
    0 -> true
    X -> (odd? (- X 1)))

(define odd?
    0 -> false
    X -> (even? (- X 1)))

Modulo:

(define even? X -> (= 0 (shen.mod X 2)))

(define odd? X -> (not (= 0 (shen.mod X 2))))

Sidef

Built-in methods:

var n = 42;
say n.is_odd;       # false
say n.is_even;      # true

Checking the last significant digit:

func is_odd(n)  { n&1 == 1 };
func is_even(n) { n&1 == 0 };

Using modular congruences:

func is_odd(n)  { n%2 == 1 };
func is_even(n) { n%2 == 0 };

Smalltalk

Using the built in methods on Number class:

5 even
5 odd

even is implemented as follows:

Number>>even
	^((self digitAt: 1) bitAnd: 1) = 0

SNOBOL4

Works with: Macro SNOBOL4 in C
Works with: Spitbol
Works with: SNOBOL4+
      DEFINE('even(n)')                         :(even_end)
even  even = (EQ(REMDR(n, 2), 0) 'even', 'odd') :(RETURN)
even_end

      OUTPUT = "-2 is " even(-2)
      OUTPUT = "-1 is " even(-1)
      OUTPUT = "0 is " even(0)
      OUTPUT = "1 is " even(1)
      OUTPUT = "2 is " even(2)
END
Output:
-2 is even

-1 is odd 0 is even 1 is odd 2 is even

SNUSP

$====!/?\==even#
      - -
#odd==\?/

SPL

> n, 0..9
  ? #.even(n), #.output(n," even")
  ? #.odd(n), #.output(n," odd")
<
Output:
0 even
1 odd
2 even
3 odd
4 even
5 odd
6 even
7 odd
8 even
9 odd

SQL

Database vendors can't agree on how to get a remainder. This should work for many, including Oracle. For others, including MS SQL Server, try "int % 2" instead of "mod(int, 2)".

-- Setup a table with some integers
create table ints(int integer);
insert into ints values (-1);
insert into ints values (0);
insert into ints values (1);
insert into ints values (2);

-- Are they even or odd?
select
  int,
  case mod(int, 2) when 0 then 'Even' else 'Odd' end
from
  ints;
Output:
       INT CASE
---------- ----
        -1 Odd
         0 Even
         1 Odd
         2 Even

SSEM

The SSEM doesn't provide AND, but for once the instruction set does allow the problem to be solved quite elegantly (albeit extravagantly slowly). Load the value of into storage address 15. The first three instructions test whether is positive, and replace it with its negation if it isn't. We then loop, subtracting 2 each time and testing whether we have got down either to 0 or to 1. When we have, the computer will halt with the accumulator storing 0 if was even or 1 if it was odd.

Note that the constant 2, stored at address 14, does double service: it is the operand for the Sub. instruction at address 6 and also the jump target returning to the top of the main loop (which is at address 2 + 1 = 3).

For larger positive or smaller negative values of , you should be ready with something else to do while the machine is working: a test run took several minutes to confirm that 32,769 was odd.

11110000000000100000000000000000   0. -15 to c
00000000000000110000000000000000   1. Test
11110000000001100000000000000000   2. c to 15
11110000000000100000000000000000   3. -15 to c
00001000000001100000000000000000   4. c to 16
00001000000000100000000000000000   5. -16 to c
01110000000000010000000000000000   6. Sub. 14
11110000000001100000000000000000   7. c to 15
10110000000000010000000000000000   8. Sub. 13
00000000000000110000000000000000   9. Test
01110000000000000000000000000000  10. 14 to CI
11110000000000100000000000000000  11. -15 to c
00000000000001110000000000000000  12. Stop
10000000000000000000000000000000  13. 1
01000000000000000000000000000000  14. 2

Standard ML

fun even n =
  n mod 2 = 0;

fun odd n =
  n mod 2 <> 0;

(* bitwise and *)

type werd = Word.word;

fun evenbitw(w: werd) =
  Word.andb(w, 0w2) = 0w0;

fun oddbitw(w: werd) =
  Word.andb(w, 0w2) <> 0w0;

Stata

mata
function iseven(n) {
	return(mod(n,2)==0)
}

function isodd(n) {
	return(mod(n,2)==1)
}
end

Swift

func isEven(n:Int) -> Bool {

    // Bitwise check
    if (n & 1 != 0) {
        return false
    }

    // Mod check
    if (n % 2 != 0) {
        return false
    }
    return true
}

Swift

// Swift has Int.isMultiple(of:Int) -> Bool

var isEven: (_:Int) -> Bool = {$0.isMultiple(of: 2)}

Symsyn

n : 23

 if n bit 0
    'n is odd' []
 else
    'n is even' []

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)]
Output:
 # O E
24:0,1
49:1,0

TI-57

This routine returns the remainder of the division by 2 of the number in the display register. It is therefore a kind of is_odd(x) function.

Lbl 9
/
2
-
CE
Int
=
×
2
=
INV SBR

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

UNIX Shell

is_even() {
	return $(($1 & 1))
}

Ursa

decl int input
set input (in int console)
if (= (mod input 2) 1)
        out "odd" endl console
else
        out "even" endl console
end if

Output:

123
odd

உயிர்/Uyir

முதன்மை என்பதின் வகை எண் பணி {{
        எ இன் வகை எண்{$5} = 0;
        படை வகை சரம்;

        "எண்ணைக் கொடுங்கள்? ") ஐ திரை.இடு;

        எ = எண்{$5} ஐ விசை.எடு;

        ஒருக்கால் (எ.இருமம்(0) == 1) ஆகில் {
                படை = "ஒற்றை";
        } இல்லையேல் {
                படை = "இரட்டை ";
        }

        {எ, " ஒரு ", படை, "ப்படை எண் ஆகும்"} என்பதை திரை.இடு;

        முதன்மை  = 0;
}};

Verilog

module main;
  integer i;

  initial begin
        for (i = 1; i <= 10; i = i+1) begin
          if (i % 2 == 0) $display(i, " is even");
          else            $display(i, " is odd");
        end
      $finish ;
    end
endmodule

V (Vlang)

fn test(n i64) {
    print('Testing integer $n')

    if n&1 == 0 {
        print(' even')
    }else{
        print('  odd')
    }

    if n%2 == 0 {
        println(' even')
    }else{
        println('  odd')
    }
}

fn main(){
    test(-2)
    test(-1)
    test(0)
    test(1)
    test(2)
}
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

WDTE

let s => import 'stream';
let str => import 'strings';

let evenOrOdd n => (
	let even n => == (% n 2) 0;
	switch n {
		even => 'even';
		default => 'odd';
	};
);

s.range 10
-> s.map (@ s n => str.format '{} is {}.' n (evenOrOdd n))
-> s.map (io.writeln io.stdout)
-> s.drain;

WebAssembly

This solution tests the low bit of the given integer, which is always 0 for even numbers and 1 for odd numbers (including negative numbers).

(module
  ;; function isOdd: returns 1 if its argument is odd, 0 if it is even.
  (func $isOdd (param $n i32) (result i32)
    get_local $n
    i32.const 1
    i32.and   ;; computes (n & 1), i.e. returns low bit of n
  )
  (export "isOdd" (func $isOdd))
)

Wren

Library: Wren-fmt
import "./fmt" for Fmt

var isEven1 = Fn.new { |i| i & 1 == 0 }

var isEven2 = Fn.new { |i| i % 2 == 0 }

var tests = [10, 11, 0,  57,  34,  -23,  -42]
System.print("Tests    : %(Fmt.v("s", -4, tests, 0, " ", ""))")
var res1 = tests.map { |t| isEven1.call(t) ? "even" : "odd" }.toList
System.print("Method 1 : %(Fmt.v("s", -4, res1, 0, " ", ""))")
var res2 = tests.map { |t| isEven2.call(t) ? "even" : "odd" }.toList
System.print("Method 2 : %(Fmt.v("s", -4, res2, 0, " ", ""))")
Output:
Tests    : 10   11   0    57   34   -23  -42 
Method 1 : even odd  even odd  even odd  even
Method 2 : even odd  even odd  even odd  even

x86-64 Assembly

evenOdd:
mov  rax,1
and  rax,rdi
ret

XBS

#>
Typed XBS
evenOrOdd function
true = even
false = odd
<#
func evenOrOdd(a:number=0){
	send a%2==0;
}
set arr:array = [0,1,2,3,4,5,6,7,9,10];
foreach(v of arr){
	log(v+" is even? "+evenOrOdd(v))
}
Output:
0 is even? true
1 is even? false
2 is even? true
3 is even? false
4 is even? true
5 is even? false
6 is even? true
7 is even? false
9 is even? false
10 is even? true

xEec

>100 p i# jz-1 o# t h#1 ms jz2003 p >0110 h#2 r ms t h#1 ms p 
jz1002 h? jz2003 p jn0110 h#10 o$ p jn100 >2003 p p h#0 h#10 
h$d h$d h$o h#32 h$s h$i h#32 jn0000 >1002 p p h#0 h#10 
h$n h$e h$v h$e h#32 h$s h$i h#32 >0000 o$ p jn0000 jz100

XLISP

XLISP provides EVENP and ODDP, or, if you prefer, EVEN? and ODD?; if one wanted to reimplement them, it could be done like this (or in other ways).

(defun my-evenp (x)
    (= (logand x 1) 0) )

(defun my-oddp (x)
    (/= (logand x 1) 0) )

Xojo

For num As Integer = 1 To 5
  If num Mod 2 = 0 Then
    MsgBox(Str(num) + " is even.")
  Else
    MsgBox(Str(num) + " is odd.")
  End If
Next
Output:
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.

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);
        ];
]
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

Z80 Assembly

Z80 Assembly has a few ways of testing if a number is even or odd:

RRC

A right rotate will set the carry if the register's value is odd and clear it if it's even. This does alter the contents of the register, so only use this method if you don't need to remember the number being tested after getting the results of the test. This is the fastest way the Z80 can test a value for even or odd, but only when testing the accumulator A

rrca
jp nc,isEven

SRA/SRL

In similar vein, there are also shift instructions. The arithmetic shift instruction retains the sign bit (bit 7) of the operand in question, while the logical shift sets bit 7 to 0.

sra a
jp nc,isEven

AND

AND 1 will change the accumulator to 1 if its value was odd, and 0 if its value was even. If you want to selectively load a 0 or 1 into the accumulator based on whether a variable is odd or even, this is the best way to do so. Like the RRC method, this test is destructive, so if you need to preserve the original value of the accumulator after the test, use the method below instead.

and &01
jp z,isEven

BIT

This method is the slowest, but it doesn't change the value in the register being tested. It works on any 8 bit register, (HL), (IX+#), or (IY+#), making it the most versatile. Although I say it's the slowest, the difference is so small and the execution time so fast that you'd never notice anyway. The Z80 can perform all these tests faster than you can blink!

bit 0,c
jp z,C_IS_EVEN

zkl

[-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") })

Ints have isEven and isOdd properties. pump, in this case, is the same as apply/map without aggregating a result.

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
[-3..4].apply("isEven").println();
Output:
L(False,True,False,True,False,True,False,True)

Zoea

program: even_or_odd 
  case: 1
        input: 2 
        output: even 
  case: 2 
        input: 4 
        output: even 
  case: 3 
        input: 1 
        output: odd 
  case: 4 
        input: 7 
        output: odd

Zoea Visual

Even or odd

zonnon

module Main;
var
	x: integer;
	s: set;
begin
	x := 10;writeln(x:3," is odd?",odd(x));
	s := set(s);writeln(x:3," is odd?",0 in s); (* check right bit *)
	x := 11;writeln(x:3," is odd?",odd(x));
	s := set(x);writeln(x:3," is odd?",0 in s); (* check right bit *)
end Main.
Output:
 10 is odd? false
 10 is odd? false
 11 is odd?  true
 11 is odd?  true