# Is this even or odd?

Note: There is not been a vanilla parity test challenge yet (There is a C/C++ one but that disallows the ability to use languages other than C/C++, and other non-vanilla ones are mostly closed too), So I am posting one.

Given a positive integer, output its parity (i.e. if the number is odd or even) in truthy/falsy values. You may choose whether truthy results correspond to odd or even inputs.

# Examples

Assuming True/False as even and odd (This is not required, You may use other Truthy/Falsy values for each), responsively:

(Input):(Output)
1:False
2:True
16384:True
99999999:False


var QUESTION_ID=113448,OVERRIDE_USER=64499;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• This isn't the first time I've confused mathematical with computational parity... this is a code site after all! – Neil Mar 21 '17 at 10:38
• Since this is pretty much one of these(1,2,3) questions, it should probably have a snippet to see all the answers. – fəˈnɛtɪk Mar 21 '17 at 13:57
• @MikeBufardeci Because "catalogue" is spelled differently based on which country you're from. For those of us in the U.S., it's "catalog". "Leaderboard" is culture-invariant. – mbomb007 Mar 21 '17 at 16:37
• @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) – Calvin's Hobbies Mar 22 '17 at 2:46
• @LucioCrusca Welcome to PPCG! The basic idea of Code Golf is to make a program in the shortest form you can. This challenge is to read an integer (positive,non-zero), and output if it is even or odd. If you are confused with something, please visit The Nineteenth Byte and ask freely. Or if you are confused with the site's policy or rules, go to the Meta. Finally, Thanks for subscribing to our community! – Matthew Roh Mar 23 '17 at 15:09

# REXX 13 BYTES

say arg(1)//2


Try it here

REXX functions and instructions

# Actually, 2 bytes

1&


Try it online!

Output is 0 if even, 1 if odd. The code is very straightforward: bitwise-AND (&) with 1 (return low bit of input).

# braingasm, 3 bytes

Takes input from stdin, prints 0 for even and 1 for odd.

;o:


; reads an integer, o checks the "oddity" (opposite of parity), : prints an integer.

edit: changed to p to o to retrofit to a breaking change in the language.

• Congratulations on being the 100th answer to this question :P – math junkie Mar 23 '17 at 14:19

# WC, 40 bytes

WIP mini language I created.

;>_0|;>(?#@8|!@3|//##@2|!@2|//#$-$-/)*$ Explanation: ;>_0| New var using the first artifact (the input number) ;>( Start a new function ? Select the first variable (reset var index) #@8| Start if statement with 9th global ("-1") as condition !@3| Print the 4th global ("1") // Terminate program # End if statement #@2| Start if statement with 3rd global ("0") as condition !@2| Print the 3rd global ("0") // Terminate program # End if statement$-$- Decrement the current variable twice / Restart context (the current function) ) End function *$             Call the current variable (the function)


Try it online!

• Cool looking language. Welcome to the site! :) – DJMcMayhem Jun 16 '17 at 20:06

# ,,,, 1 byte

œ


Yeah, yeah, a builtin... For anybody wondering about the choice of character, it's supposed to be odd or even or o or e.

However, I do have other solutions.

## 2 bytes

1&


### Explanation

1&

implicit input
1   push 1
&  pop input and 1 and push input & 1 (bitwise AND)
implicit output


## 2 bytes

2%


### Explanation

2%

implicit input
2   push 2
%  pop input and 2 and push input % 2 (modulo)
implicit output

• œ yeah a new solution, and a new builtin – Matthew Roh Jul 12 '17 at 3:28

# x86_64 Linux machine language, 5 bytes

0:       97                      xchg   %edi,%eax
1:       83 e0 01                and    $0x1,%eax 4: c3 retq  To try it, compile and run the following C program #include<stdio.h> const char f[]="\x97\x83\xe0\1\xc3"; int main(){ for( int i = 0; i < 10; i++ ) { printf("%d %d\n", i, ((int(*)(int))f)(i) ); } }  Try it online! # Aceto, 5 bytes ri2%p  r reads input i converts to integer 2% takes the number modulo 2 p prints the answer  Try it online! # Underload, 5 bytes ():aS  Underload doesn't really have a concept of Truthy/Falsey, so this is empty/nonempty output for odd/even respectively. Input should be in unary (as some number of ~) between the a and the S. ## Explanation () pushes the empty string. : duplicates it and () wraps the top stack element in parenthesis, meaning the stack now looks like "", "()". The input now appears in the program, meaning it is executed as code. ~ is the swap instruction in Underload, meaning that an even input is an even number of swaps, which doesn't affect the stack, and an odd input is an odd number of swaps, which has the same effect as a single swap. S outputs the top stack element, which will be either () if the input was even, and if the output was odd. I mentioned that Underload doesn't have Truthy/Falsey, but the common way to represent booleans as Underload code that either swaps or doesn't swap, meaning that the cheaty one-byte program S technically works as a valid submission. # Pyt, 2 bytes 2%  Explanation  Implicit input 2% Mod 2 Implicit print  Odd is truthy, even is falsy Try it online! Alternatively, also 2 bytes 2|  Explanation:  Implicit input 2| Is it divisible by 2? Implicit output  Even is truthy, odd is falsy Try it online! # Fortran 95, 31 28 bytes Thanks to @georgewatson for saving three bytes! function h(i) h=mod(i,2) end  Returns 0 if even, 1 if odd. Try it online! • Since input is always a positive integer, you could save 3 bytes by using mod. – georgewatson Feb 1 '18 at 10:18 • @georgewatson Thanks! – Steadybox Feb 1 '18 at 14:19 # Flobnar, 6 bytes & %@ 2  Try it online! (requires the -d flag) I don't think it's going to get much shorter than this. ## CHIP-8 assembly, 22 bytes 0x6001 F10A 410F 120C 8210 1202 8226 8F03 FF29 D005 1214  Takes in a number entered by the user, until it is terminated by the user pressing the F key, and prints out to the screen 0 if it's odd, or 1 if it's even. The CHIP-8 had 16 8-bit registries (V0 to VF), with VF mostly being used for carry operations. The ROM was loaded into memory at address 0x200, which is why the jump operations are offset. It also contained display-representations of the numbers 0-9 and letters A-F in memory at 0x00, so that a programmer need not create them. The code works like this: 0x200: 60 01 Set V0 to 0x01. 0x202: F1 0A Wait for a key to be pressed, and enters the value into V1. 0x204: 41 0F Skip the next instruction if V1 does not equal 0x0F. 0x206: 12 0C Jump to instruction address 0x20C. 0x208: 82 10 Assign the value of V1 into V2. 0x20A: 12 02 Jump to instruction address 0x202. 0x20C: 82 26 Store the least significant bit of V2 into VF, left-shift V2 by one bit, and store the shifted value into V2. 0x20E: 8F 03 Set VF to VF XOR V0 (V0 is set previously to 1, so this is equivalent to NOT VF). 0x210: FF 29 Set the memory address pointer (I) to the character representation of the value in VF. 0x212: D0 05 Draw the data from the address pointer I to the screen, at pixel (0, 0), with a width of 5 pixels (the height is always 8 pixels). 0x214: 12 14 Jump to instruction address 0x214 (i.e., loop indefinitely).  # Z80Golf, 9 8 bytes 00000000: d5d2 0380 e601 ff76 .......v  Try it online! ### Disassembly start: push de jp nc,$8003
and 1
rst $38 halt  Golfed a byte using the "input loop at start" pattern:  push de ; Push 00 00 (return address) to the stack jp nc,$8003 ; Escape the loop if carry is set (EOF)
; otherwise take next input and return to the start of the program


## Previous solution, 9 bytes

00000000: cd03 8030 fbe6 01ff 76                   ...0....v


Try it online!

### Disassembly

start:
call $8003 jr nc, start and 1 rst$38
halt


Accepts the decimal input (binary, octal, hexadecimal, or any other even base would work), and outputs ASCII 0 for even, 1 for odd.

call $8003 calls getchar, which stores the next char to register a, or sets the carry flag on EOF. Since the only significant data is the last char, the program simply calls getchar repeatedly until EOF. and 1 takes the parity, rst$38 is a golf idiom for call putchar, and halt terminates the program.

00000000: cd03 8030 fbe6 31ff 76                   ...0....v


Try it online!

Limiting the input to decimal or lower even bases, we can get more readable result ('0' = $30 and '1' =$31) by changing and 1 into and \$31. Also works for hexadecimal if you use 0123456789pqrstu, case sensitive :)

# Little Man Computer, 31 bytes, 5 instructions

INP
SUB 5
BRP 1
OUT
DAT 2


Which boils down to this once assembled into RAM:

901 205 801 105 902 002


Outputs $$\ 1 \$$ for an odd number and $$\ 0 \$$ for an even number.

A online emulator can be found here, though you may need to increase the speed to avoid waiting a painfully long time (if anyone finds a better online version, please enlighten me).

# Alchemist, 79 35 bytes

-43 bytes thanks to ASCII-only!!

-1 byte thanks to Jo King!

_->s+In_i
e+i->
0e+i->e
s+0i->Out_e


Outputs 0 for even and 1 for odd, try it online!

## Ungolfed

• You could probably golf the outputs to... 0 and 1 or "" and "1" or something – ASCII-only Jan 29 at 8:05
• 56? – ASCII-only Jan 29 at 8:07
• if other outputs (0/1 for odd/even) are allowed, 36 – ASCII-only Jan 29 at 8:10
• @ASCII-only That doesn't work since the output can occur before the input. 35 bytes should work deterministically – Jo King Mar 13 at 6:43

# Turing Machine Code, 99 bytes

0 * * r 0
0 _ _ l 1
1 0 0 * A
1 2 2 * A
1 4 4 * A
1 6 6 * A
1 8 8 * A
A * * * halt-e
1 * * * halt-o


Outputs via the halt state, terminating in state halt-e for even or halt-o for odd.

Try it online.

• wonder if outputting via the item under the cursor would be valid – ASCII-only Apr 12 at 7:15

# Come Here, 68 bytes

ASKi0CALLi*256iCOME FROM SGN(i//256)1CALL(i//256)iTELL48+(iMOD2)NEXT


Less golfed:

ASK i
0 CALL i*256 i
COME FROM SGN(i//256)
1 CALL (i//256) i
TELL 48 + (i MOD 2) NEXT


COME HERE uses integers internally, but handles input and output as strings; unfortunately, the string encoding it uses really isn't all that helpful for working with input as numbers. In this case, we have to repeatedly divide by 256 until we get a value that is less than 256, in order to get the last character.

If little-endian (rather than big-endian) input is allowed, we can use this shorter version (22 bytes) instead:

ASKiTELL48+(iMOD2)NEXT


Prints 0 for even, and 1 for odd.

# Pyramid Scheme, 221 bytes

    ^        ^ ^
/ \      /l\-
/set\    /oop\
^-----^  ^-----^
-    ^- /*\   / \
^- ^---^ /set\
/#\ -^  -^-----^
^--- /-\  -    /-\
/l\  ^---^     ^---^
/ine\/1\  -     -  /2\
--------           ---


Try it online!

Outputs 0 for even and 1 for odd.

Pyramid Scheme has no modulus, no integer division, and no bitwise operators. The best approach I could conceive was repeatedly subtracting two from the input until either it or its predecessor is zero, then printing the final value.

This program translates rather easily to true Scheme. I have to say, that's my favorite part of this language—it's very nearly a Scheme dialect in its own right, despite being a joke!

(define n (read))
(do ()
((= 0 (* n (- 1 n))))
(set! n (- n 2)))
(display n)


Try it online!

# Re:direction, 7 bytes

♦♦
▼►
◄


Outputs 1 if odd, and 0 if even. Basically works by alternating between the left and right side until a ▼ is found (▼ is at the end of the input) and then outputs depending on which side it is on.

Try it online!

# Toi, 6 bytes

(r[rr]


Try it online!

Toi is a language that only knows sets. The memory is a set S that starts as the empty set. The input number can be given as a von Neumann ordinal, constructed using "ua"*n, or alternatively the input number can be represented by the nesting level using "u"*n. u nests the context S, and a changes S to $$\S \cup \{t \mid t \in s, s \in S\}\$$ (from the esolangs wiki article).

( cond [ stuff ] is a while loop that performs stuff while applying cond on S yields a non-empty set. The commands in cond are unapplied before executing into stuff.

r changes S to $$\\{t \mid t \in s, s \in S\}\$$ essentially removes a layer of nesting. This effectively decrements the number represented by S by 1.

So, the meaning of ( r [ rr ] is the following: while r on S is non-empty (i.e. while S-1 is not 0), perform rr (decrement S twice).

The parity is left on S, $$\\{\{\}\}\$$ if the input is odd, and $$\\{\}\$$ otherwise.

# PARI/GP, 6 bytes

n->n%2


Mod 2.

# CJam, 4 bytes

q~2%


Try it online!

Simple mod by 2. Outputs 1 for odd, 0 for even.

# Julia 0.5, 5 bytes

isodd


Try it online!

# Java, 91 bytes

enum d{;public static void main(String[]a){System.out.println(Long.parseLong(a[0])%2==0);}}


Takes number as first command line argument and outputs to STDOUT.

## bc, 9 bytes

Output is 1 for odd, and 0 for even.

read()%2


Try it online!

A trailing newline is necessary to run successful, and it is included in the bytes count. The read() function works only for numerical input.

# Applescript function, 26

on f(i)
return i mod 2
end


# Test calls

log f(1)
log f(2)
log f(3)


# Go, 26 bytes

func(i int)int{return^i&1}


Returns 1 for even and 0 for odd.

Try it online!

# Scala, 15145 3 bytes

_%2


Returns 0 if it's an even number and 1 if it's odd

This is equivalent to (i:Int)=>i%2.
However, this needs to be assigned to a variable of type Int=>Int, otherwise the compiler will complain.
The whole code would look like this:

val x: Int => Int = _%2

• Just a tip but you can reduce this by one byte by doing <1 instead of ==0. – Stefan Aleksić Mar 25 '17 at 14:46
• I don't think that's cheating. See here. Notice that Java 8 lambda solutions often leave off the type. – Brian McCutchon Mar 26 '17 at 23:44
• Is the <1 even needed? would it not return 0 if even and 1 if odd? – fəˈnɛtɪk Mar 27 '17 at 14:49
• Depends if we need a boolean, but I guess returning 0 and 1 works too. Thanks! – therealfarfetchd Mar 27 '17 at 19:37

# Swift, 18 bytes

let f={n in n%2<1}

• Can be shortened to let f={n in n%2} which would return 0 for even and 1 for odd, saving 2 bytes – Mr. Xcoder Apr 11 '17 at 14:09

# Chip, 2 bytes

For the simple case:

Aa


This only handles one-byte numbers, either a single ASCII digit or a 1 byte unsigned integer (because ASCII code points for odd digits are themselves odd). This works like the &1 bitmask used in many other answers. If multiple bytes are provided, this will treat each new byte as a separate input. Outputs 0x0 for even and 0x1 for odd.

By adding e*f, we can get output in ASCII (5 bytes):

Aae*f


Try it online!

# 23 + 3 = 26 bytes

For the complex case:

 Svvvvvvvv~t
azABCDEFGH


This handles numbers of any length, ASCII or unsigned integer as before (big endian so that least significant bit is still last). Requires either a null terminator, or the -z flag (as shown in the byte count) to detect the end on the input. Like above, outputs 0x0 for even and 0x1 for odd.

Again, we can add e*f to get ASCII output (25 + 3 = 28 bytes):

*fSvvvvvvvv~t
eazABCDEFGH


Try it online!