# 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

# Carrot, 5 bytes

#^F%2


Try it online!

Note: this is a trivial answer. Please do not vote. I am only posting this for completion.

### Explanation

#^                // set the stack to the input
F               // convert it to a float
%2             // take the modulo 2 of it
// implicit output

• That's okay. Every answer else is trivial too. At least it's not a builtin. – Matthew Roh Mar 23 '17 at 9:32
• Why do you have to convert to float? – Hello Goodbye Nov 14 '19 at 16:27
• @HelloGoodbye Because it is by default a string, although yes, I should work just as well – user41805 Nov 14 '19 at 16:57
• ah, makes sense – Hello Goodbye Nov 14 '19 at 17:05

# APL (Dyalog), 3 bytes

Full program body:

2|⎕


Try it online!

Alternatively:

2⊤⎕


Try it online!

| is modulus, ⊤ is base-convert, ⎕ is numeric input prompt. Handles any numeric array.

I've found 40 functions which can also do the job in 3 bytes. List and try them all online!

# Haxe, 22 bytes

function(x)return x%2;


Test it online!

Haxe is a high-level, strictly typed language designed to be compiled across many different platforms. While it doesn't have any form of lambda expressions, it does have one unique property that allows for interesting golfing: everything is an expression. This allows you to do interesting things that aren't possible in most similar languages, such as b>0&&return b. In this particular case, it allows us to remove the brackets that would normally be required in a function definition.

• High level language, low level answer (lol) – Matthew Roh Mar 23 '17 at 13:37

# Qwerty-RPN, 4 bytes

@2%#


Explanation:

@    Input number
%  ...modulo...
2   2
# print


# Beeswax, 6 bytes

_2~,%{


Explanation:

_        Create a bee flying horizontally   [0,0,0]
2       Set top to 2                       [0,0,2]
~      Swap top and 2nd values            [0,2,0]
,     Take value from STDIN as int       [0,2,7]
%    Modulo: top % 2nd                  [0,0,1]
{   Print top                          [0,0,1]


Try it online!

## Ook!, 79 64 bytes

Update: 15 bytes shorter by removing the whitespaces, thanks to Okx.

This is a joke esoteric language, meant to be trivially isomorphic to brainfuck by substituting each command with an Orangutan phrase. This is my first time using it.

Ook.Ook.Ook!Ook?Ook.Ook!Ook.Ook?Ook.Ook!Ook?Ook!Ook?Ook.Ook!Ook.


Try it here! Give input as unary. Output is 1 for odd numbers, and nothing for even ones.

Explanation:

The above script is a direct translation of the 8 bytes brainfuck answer by @Dennis:

+[,>,]<.


Ook! has only 3 distinct syntax elements: Ook., Ook? and Ook!. These are combined into groups of two, and the various pair combinations are mapped to the brainfuck commands.

Substitution table:

>   Ook.Ook?
<   Ook?Ook.
+   Ook.Ook.
-   Ook!Ook!
.   Ook!Ook.
,   Ook.Ook!
[   Ook!Ook?
]   Ook?Ook!

• You can golf it by removing the newlines. – Okx Mar 23 '17 at 14:27
• @Okx On a second look, the online interpreter from my answer works with no whitespace delimiter. Cool! That means I can remove the spaces too. Thanks for pointing that out. I've read the wiki and the Ook! creator's page and only the newlines were said to be ignored, nothing about the spaces. – seshoumara Mar 23 '17 at 15:13
• Is there really any point to golf it? It is equivalent to BF, just with the byte count multiplied by 8, so golfing it is essentially the same as golfing BF. There's a reason it's not on TIO. – null Aug 14 '20 at 4:45
• Looking now at it, no, you're right. But back then if I wouldn't have done it, I wouldn't have known that it works also if you remove the newlines and especially the spaces. I don't think I made another answer in Ook since then. – seshoumara Aug 14 '20 at 20:26

## Gibberish, 8 bytes

eli2gmeo

eli      - read line, convert to integer
2gm   - push 2, push modulo of previous value by 2
eo - output stack


Outout 0 for even and 1 for odd

# J-uby, 6 bytes

:even?


In J-uby, Ruby's symbols are callable. Fixnum#even? in Ruby (predictably) returns whether a number is even or not. It can be called like so:

f = :even?
f.(2) #=> true
f.(3) #=> false


J, 8 chars

<&1@:|~&2


It's just a composition of

<&1


which flips 0 for 1, and

|~&2


which is mod 2.

The @: just composes the two functions together

• You don't need <&1@. It's up to us which Boolean corresponds to which parity. Also, 2&| saves a byte. Try it online! – Dennis Mar 25 '17 at 12:40
• Welcome to the site! – caird coinheringaahing Mar 31 '17 at 6:40

# Elisp, 12 10 bytes

(%(read)2)


(read) evaluates to the input, and the (% ...) expression is then evaluated. Outputs 1 for odd, 0 for even.

Test cases:

(Input):(Output)
1:1
2:0
16384:0
99999999:1

Edit: Saves 2 bytes thanks to @Dylan, for asking if it was possible to leave out the spaces in a Elisp expression. Turns out the answer is yes!

## Python REPL, 3 bytes

_&1


Explanation: Taking bitwise and with 1 gives True when even else False

• Just so you know, the downvote was cast automatically by the Community user when you edited your answer. I consider this a bug. – Dennis Mar 26 '17 at 15:08
• Note to voters: _ is the value of the last expression in an interactive session, so the code can be used like this. Per consensus, this is currently a valid form of taking input. – Dennis Mar 26 '17 at 16:08
• Welcome to PPCG! – Pavel Mar 26 '17 at 19:40
• @ГригорийПерельман thank you – Aashutosh Rathi Mar 28 '17 at 7:33
• @Dennis thanks for edit 👍 – Aashutosh Rathi Mar 28 '17 at 7:34

# J, 2 bytes

2|         NB. remainder of arg / 2

So 0 = true (even), 1 = false (odd)
2| 7   => 1
2| 10  => 0

• This doesn't look right. I get a syntax error. I think you need another byte: 2|] or 2&| – Adám May 8 '17 at 8:55

# Acc!!, 43 bytes

N
Count i while _/10 {
N-_%2*2
}
Write _+41


Because of quirks of the input mechanism in Acc!!, the input number (given on stdin) has to be terminated with a signal value--in this case, a tab character. The code outputs 2 if the number is even, 0 if it is odd.

### Explanation

# Read a character's ASCII value into the accumulator
N
# Loop while accumulator intdiv 10 is greater than 0 (i.e. acc >= 10)
Count i while _/10 {
# Read another ASCII value, subtract (current acc % 2) * 2, and store back to acc
N-_%2*2
}
# At the end of the loop, we know we just read a tab character (ASCII 9). This means the
# acc value is 9 if the previous digit had an even ASCII value, or 7 if it was odd. We
# add 41 to convert to the ASCII codes of 2 and 0, respectively, and write to stdout.
Write _+41


# Scala, 9 bytes

(_:Int)%2


This outputs 1 for odd, 0 for even

# Clojure, 15 bytes

#(= 0(rem % 2))


Ignoring the obvious built-ins, this is probably as short as it gets.

Checks if the argument divided by 2 equals 0. Nothing fancy. Returns true for even numbers, false for odd.

Beaten by brainfuck!

# Dogescript, 32 29 bytes

such f much n
return n%2
wow


Returns 1 if n is odd, 0 otherwise.

• You could still keep the Dogescript syntax and save 3 bytes: such f much n return n%2 wow. There's no need to convert a truthy value to boolean. – Grant Miller Mar 31 '17 at 20:44

# 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! :) – James 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! # Whitespace, 30 bytes [S S S T S N _Push_2][S N S _Duplicate][S N S _Duplicate][T N T T _Read_STDIN_as_number][T T T _Retrieve][S N T _Swap_top_two][T S T T _Modulo][T N S T _Output]  Letters S (space), T (tab), and N (new-line) added as highlighting only. [..._some_action] added as explanation only. Outputs 0 for even, 1 for odd. Try it online. Explanation (with 5 as input): Command Explanation Stack Heap STDIN STDOUT SSSTSN Push 2 [2] {} SNS Duplicate top (2) [2,2] {} SNS Duplicate top (2) [2,2,2] {} TNTT Read STDIN as number [2,2] {2:5} 5 TTT Retrieve [2,5] {2:5} SNT Swap top two [5,2] {2:5} TSTT Modulo [1] {2:5} TNST Output top as number [] {2:5} 1  # Python 2, 13 bytes lambda n:~n&1  Try it online! No shorter than the other non-REPL Python answers, but uses slightly different logic. Takes the bitwise complement of the input number (-x-1) and performs a BITWISE AND on it. Returns 1 if the complement is odd, and 0 if the complement is even - and therefore returns 1/0 if the original number was even/odd. (Could be shortened by 1 byte by removing the complement ~ if 0=True and 1=False is allowable.) # 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

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