# 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
Commented Mar 21, 2017 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. Commented Mar 21, 2017 at 13:57
• @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) Commented Mar 22, 2017 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! Commented Mar 23, 2017 at 15:09
• As @HelkaHomba mentioned, zero is not positive; what is the expected result for input of zero? Or do we not care? Commented Mar 26, 2017 at 18:42

# Pyramid Scheme, 108 92 bytes

   ^
/-\
^---^
-^ ^-
-^-
/^\
^---^
-^ /#\
/-\---^
/ 1 \ /l\
-----/ine\
-----


Try it online!

Outputs -2 for odd numbers and 0 for even ones. This can be swapped by switching the top pyramid for + instead of -. This is basically equivalent to (-1)**int(input) - (-1)**0

## Microsoft Word Math Autocorrect, 40 bytes

0$->$0
1$->$1
2$->$0
3$->$1
4$->$0
5$->$1
6$->$0
7$->$1
8$->$0
9$->$1


Then make a new equation. Separate each digit with a space, or this will not work. When you type your last digit, it will be replaced by either a $1 (if it's odd) or$0 (if it's even).

For example, to input the number 942, type 9 4 2$, which becomes 9 4$1, telling me it's odd. As a bonus, this works for all even bases up to 10.

# MAWP, 36 bytes

%@_1A[1A~25WWM~]%[{1A{1M}<0:.>}2A]1:


## Explanation

It uses the same logic as all the other programs, but MAWP does not have a modulo operator.

The workaround is repeately deducting 2 from the number until we reach 0 or 1.

%@_1A[1A~25WWM~]% snippet used for inputting multi digit numbers
[                 loop if top of stack != 0
{1A{1M}<0:.>}    if number-1=0 print 0 and end program
2A]               subtract 2 from the number
1:                once loop ends, print 1


4 digit and higher numbers take very long to check in the online interpreter.

Try it!

• I've actually made a modulo function that is pretty short in my FizzBuzz answer codegolf.stackexchange.com/a/207427/92080
– Dion
Commented Aug 11, 2020 at 5:04
• Wow, that's pretty cool. Should put that in the language examples. Commented Aug 11, 2020 at 5:08

# Check, 4 bytes

>2%p


Explanation: >2 pushes 2 onto the stack, % preforms modulus with the implicit input, and then p prints the result.

• What is "Check"? Commented Jun 17, 2017 at 7:49
• Commented Jun 17, 2017 at 21:55

# Bound, 3 bytes

i?.


Explanation:

i # Gets input and adds to stack if its an integer
? # Pops the top element and check if its even (0 is false, 1 is true)
. # Displays the stack


Try it online!

# Kotlin, 19 bytes

fun a(n:Int)=n%2==0


This was surprisingly simple. And the code is pretty self explanatory.

# ARM Thumb-2 machine code, 4 bytes

07c0 4770

        .syntax unified
.arch armv6t2
.thumb
.globl is_odd
.thumb_func
// Standard C calling convention
// Input: uint32_t r0
// Output: r0 == 0 if even, else odd
is_odd:
// Shift out everything but the lowest
// bit, leaving odd numbers as
// 0x80000000 and even numbers as 0.
lsls    r0, r0, #31
// Return
bx      lr


Very simple. Shifts everything but the lowest bit into oblivion via lsls and returns.

Odd numbers will return nonzero and even numbers will return zero. It follows standard C calling convention.

0x01234567 << 31 = 0x80000000
0x12345678 << 31 = 0x00000000


You can't get any shorter than that.

For the reference, and{s} r0, #1 is a wide instruction.

# Python - 24 bytes

n=int(input())
print(n%2)


Hooray for built-ins! This program should be fairly easy to understand. Assumes n has not been inputted already into the program. If it has, only the second line is necessary, and this can be golfed down to 10 bytes.

# Stack Cats + -mn, 6 bytes

[:^*_:


Try it online!

mirrored (done with -m flag):

[:^*_:_*^:]


Returns 1 for odd and and -1 for even. The n flag is used for numeric, rather than codepoint io.

Stack Cats is a very interesting language. Stack Cats performs operations on an infinite tape of bottomless stacks of arbitrary precision integers. It requires mirror symmetry, and most of the mirroring exactly undoes the previous operation. Despite this, Stack Cats is Turing complete, and that is most easily achieved by using a <(...)*(...)> construct that skips the entire first half. However, that construct would require more bytes than the approach I used. The first part [:^ moves the input to the top of the next stack and duplicates it. Since the inputs are terminated with -1 the stacks now looks like this:

         [i]
... [-1] [i] ...
^


where i is the input. The next part *_ determines the parity of the input by subtracting the input from the input with its least significant bit flipped, leaving 1 for odd, or -1 for even. The stacks now look like this:

         [r]
... [-1] [i] ...
^


where i is the input and r is the result. Next comes the hard part: ensuring the first half doesn't undo the second. That is done by a single : which flips the top two values of the stack, which now looks like this:

         [i]
... [-1] [r] ....
^


_*^ then performs some operations on the input, leaving random garbage in its place, and the result unchanged. The final :] moves the result to a place it is printed (because the current stack is outputted, without any trailing -1s). The final stack looks like:

    [r]
... [-1] [random garbage] ...
^


# APL (Dyalog Unicode), 11 bytes

⎕←2|⎕


Try it online!

Explanation:

⎕← print to stdout
2| parity of
⎕ input

• this is only 5 bytes using SBCS Commented Mar 19, 2022 at 11:19

# dotcomma, 74 bytes

[[,.][.][.].,].[[[[,.][[].[],][[].[],].,][[,][[].[],][[].[],].],[],.][.].]


Dotcomma is a language I recently invented, designed to do things in an interesting way with as few instructions as possible. In order to accomplish this, there are two operators (predicatably . and ,) which can do entirely different things depending on context. This answer's explanation will be a somewhat high level explanation of how this program works. To see some simpler examples, check out the examples in the page linked in the title.

The first part of this program, [[,.][.][.].,], adds 2 to the inputted number. The [,.] block will take a number from the queue (which will contain the input), add it to two [.] blocks (equal to 1 each), and put it back in the queue. The . between the two main blocks creates a loop.

To make the loop easier to understand, here's the code broken into more manageable pieces:

[[,.][.][.].,].[
[
[[,.][[].[],][[].[],].,]
[[,][[].[],][[].[],].],[],.
][.].
]


The first part of the loop, on line 3, will take the current number from the queue and subtract 2 from it. It then puts it back in the queue, and the second part tests whether that number minus 2 is negative. If so, the loop ends.

The result is the number in the queue being either 0 if the input was even, or 1 if the input was odd.

# !@#\$%^&*()_+, 14 9 bytes

^(1*1*)+#


(1 represents character \x01.)

Try it online!

Someone created an Esowiki page for this language and put a badly-golfed parity program there, which motivated me to create this program. It inputs n and inverts 0 n times.

I only now noticed I made an answer for this challenge, so I decided to golf it. This is a straightforward port of Dennis' BF answer. Input is unary with the character \x00. Output 1 if it's odd.

Find this unsatisfying? Here's output 1 if it's even, in still 9 bytes.

^(2**)+*#


## Desmos, 12 bytes

mod(i,2)
i=0


1 is falsey odd number and 0 is truthy even number.

• Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Desmos page for ways you can golf your program! You might also want to provide a permalink so others can easily test your code. Commented Mar 16, 2022 at 3:01
• Hardcoding input as a variable is discouraged. The accepted way to take input is through functions. As such, your code should actually be 13 bytes: f(i)=mod(i,2). Commented Apr 26, 2022 at 7:11

# Excel VBA, 9 bytes

An anonymous immediate window function that bit masks all but the lowest bit of input from range [A1] and outputs to the immediate window

?1And[A1]


# WolframAlpha, 6 bytes

x mod2


Try it online!

This will output 0 if the value is divisible by 2 and a non-zero value ("truthy") otherwise.

However, if that is not good enough, there's an alternative 11-byte solution using the floor function:

⌊x⌋mod2


Try it online!

Note: Byte count in UTF-8 counted using this resource.

# K (ngn/k), 5 2 bytes

2!


Try it online!

-3 bytes thanks to Jo King

0 for true, 1 for false.

• You can just do 2! instead of an explicit block
– Jo King
Commented May 6, 2022 at 14:40

## Pascal, ≥ 6 B

odd(x)


where x is an integer variable or expression returns the Boolean value true if x mod 2 = 1, otherwise false.

# GBZ80machine code, 1 byte

Given an input in register A, this outputs in the carry flag such that 1 is odd and 0 is even.

0F


Disassembly:

rrca


This instruction rotates register A right once, but with the carry flag treated as bit -1 only for the right end. This instruction can be confused with rrc a, which is a two byte (CB 0F) instruction using a genericized pattern for other registers and which updates the zero flag.

Bit 0 determines parity. Performing a rotation right through carry puts bit 0 in the carry flag.

# C (gcc), 10 bytes

Uses the -D compiler flag to define a macro.

-Df(i)=i&1


Try it online!

# Thunno 2, 1 byte

E


Attempt This Online! Uses $$\1\$$ (true) for even, and $$\0\$$ (false) for odd.

ɗ


Attempt This Online! Uses $$\0\$$ (false) for even, and $$\1\$$ (true) for odd.

# (,)ds, 16 14 Chars or $$\14\log_{256}(3)\approx\$$ 2.77 Bytes

((()),,((())))


Accepts input in unary as a sequence of null bytes (easiest way to make it is by adding %00 to the input section in the URL), and outputs -1 for odd and 0 for even.

TIO

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

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

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

# x86 machine code, 2 bytes

00000000  a8 01                                             |..|
00000002


Sets the zero flag if the value in register A is even.

# R, 10 bytes

!scan()%%2


If you can get away with assuming n is the value, !n%%2 works.