# 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

# Brachylog, 3 bytes

%₂0


Try it online!

### Explanation

Well…

%₂0     Input mod 2 = 0


# Cardinal, 7 bytes

%++~:M.


Outputs truthy if odd falsy if even

Try it online!

# AHK, 21 Bytes

a=%1%
Send % Mod(a,2)


Once again, I can't use inputs directly in functions so I have to store it as another variable.

# C, 15 bytes

#define f(n)n&1


Returns 0 if even, 1 if odd.

# Common Lisp, 7 Bytes

#'evenp


Built-in function that checks parity. Barely beating Java!

# ><>, 4 + 3 = 7 bytes

Outputs 1 for odd and 0 for even. Execute using -v (+ 3 bytes).

2%n;


Try it online!

## QBIC, 7 5 bytes

:?a%2


This prints 0 for even values, and 1 for odds.

Explanation:

:   get a number from the cmd line args
?   PRINT
a%2 The input modulo 2 (1 for odds, 0 even)


## dc, 4 bytes

Output is 1 for odd, and 0 for even.

?2%p     # read input, push 2, do modulo, print


Try it online!

I think for stack-based languages, I can assume the input is already on the stack, and that I can leave the output on top when done. This would be similar to how I/O is allowed for functions.

Stack I/O: 2 bytes

2%


# yup, 15 bytes

{0e0:e---}00e--


Try it online!

Much nicer than I thought it might be! I don't presently have a modulus algorithm (though there most likely is one), but this is considerably simpler. It takes input from the stack and leaves output on the stack.

## Explanation

{0e0:e---}00e--   stack     | explanation
[n]       | input from top of stack
{        }        while top of stack is positive:
0                [n 0]     | push 0
e               [n 1]     | pop x, push e^x
0              [n 1 0]   | push 0
:             [n 1 0 0] | duplicate
e            [n 1 0 1] | pop x, push e^x
-           |n 1 -1]  | subtract
-          [n 2]     | subtract
-         [n-2]     | subtract
now, either -1 is on the stack for odd, or 0 for even
0       [c 0]     | push 0
0      [c 0 0]   | push 0
e     [c 0 1]   | pop x; push e^x
-    [c -1]    | subtract
-   [c+1]     | subtract (adds)


# Befunge 98, 4 bytes

&2%.


Try it Online! (It may take a while because of how it ends)

&       Take input
2%     Mod 2
.    Print
&       The IP wraps around and hits the "take input" again. Because of the
way TIO's '98 handles & on EOF, this ends the program after a minute.


This answer is very similar to Befunge 93, but doesn't need the @ to end.

# Befunge 93, 5 bytes

&2%.@


Try it Online!

&        Take input
2%      Mod 2
.@    Print and exit


This answer is very similar to Befunge 98, but it needs the @ to end because & pushes the last number in the input on EOF

# V, 87 6 bytes

Àé1òhD


Try it online!

Outputs 1 for odd numbers and nothing (an empty string) for even numbers.

Àé1                   " argument times insert a 1
" this converts input to unary
" and now the cursor is at the end of the line
ò                  " recursively do:
h                 "  move 1 to the left and
D                "  delete everything from the cursor to the end of the line
"  this effectively removes 2 characters at once until
"  a breaking error occurs at which point
" implicit ending ò

• Cool approach, I like it! Alternate (but very similar) approach: Àé1Ó11 Commented Mar 21, 2017 at 20:34

# J, 3 bytes

2&|


Explanation:

2&|
|    this does mod, only with the order of the operands reversed
2      the number 2... derp
&     attaches 2 to | so it can be the left operand
the right operand is implied due to tacit programming

• Alternatively, 2|]. Commented Mar 21, 2017 at 18:37
• um... what does the ']' do? Commented Mar 21, 2017 at 18:51
• Well, it means "yield right argument", and is often the identity function. A train of three verbs (or a constant followed by two verbs, as in this case) constitutes a "fork", in which the middle "tine" of the verb (in this case, %) is applied the result of the application on each of the outer tines. If a constant is invoked in this way, it simply returns the constant. So, for an argument y, (2|])y is equivalent to (2 | (] y)), which is 2 | y. Commented Mar 21, 2017 at 19:24
• An APL expression for all the 3-byte J expressions that are valid answers
Commented Mar 23, 2017 at 10:59

## Bash + coreutils, 11 bytes

Output is 1 for odd numbers, and nothing for even ones. This is a full program. There is another bash answer by Digital Trauma, but that one is a function, however it is in pure bash.

seq $[$1%2]          # give 'input % 2' as argument to seq. Notice that 'seq 0'
#doesn't print anything.


Try it online!

I use seq, because it is 1 byte shorter than echo, but it has a different truthy / falsy mapping.

# tinylisp, 18 bytes

There's a library function for that.

(load library)odd?


The function itself is odd?--call it like (odd? 12). Try it online!

Writing a function from scratch is 28 bytes (TIO):

(d o(q((n)(i(l n 2)n(o(s n 2


This defines o as: if n is less than 2, return n, else recurse with n-2.

# LibreLogo, 19 bytes

Code:

print int input "%2


Result:

Returns 0 for even numbers, and 1 for odd numbers.

# Pip, 3 bytes

a%2


Try it online!

Explanation:

a   is auto-read from the command line
%2  Modulo 2 --> yields a 0 for even, 1 for odd
The result of the last statement is auto-printed.


## Jellyfish, 6 bytes

p|i
2


Try it online!

Print (p) the input (i) modulo (|) two (2).

# 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. Commented Mar 23, 2017 at 9:32
• Why do you have to convert to float? Commented Nov 14, 2019 at 16:27
• @HelloGoodbye Because it is by default a string, although yes, I should work just as well Commented Nov 14, 2019 at 16:57
• ah, makes sense Commented Nov 14, 2019 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) Commented Mar 23, 2017 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
Commented Mar 23, 2017 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. Commented Mar 23, 2017 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. Commented Aug 14, 2020 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. Commented Aug 14, 2020 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, 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! Commented Mar 25, 2017 at 12:40
• Welcome to the site! Commented Mar 31, 2017 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. Commented Mar 26, 2017 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. Commented Mar 26, 2017 at 16:08
• Welcome to PPCG! Commented Mar 26, 2017 at 19:40
• @ГригорийПерельман thank you Commented Mar 28, 2017 at 7:33
• @Dennis thanks for edit 👍 Commented Mar 28, 2017 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&|
(_:Int)%2