# 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

# TacO, 29 bytes

   2i i
i -+*2
@+%#?v
1


Outputs 1\n if even, or just \n if odd.

This takes all multiples of 2 from 2 to 2n, removes all the ones in which n - i ~= 0 and sets the rest to 1, then sums that list.

Try it online!

# Perl 6, 4 bytes

*%%2


Try it

This is a WhateverCode lambda closure that takes one positional argument.

## Expanded:

*   # the parameter   (turns the expression into a WhateverCode)
%%  # is divisible by
2   # two


# Wise, 4 bytes

:><^


Try it Online! (Takes input through command line arguments for now)

Prints 1 for odd, 0 for even.

        Implicit input
:       Duplicate
><     Bitshift right, then left, which changes the least significant bit to 0
^    Xors with original
Implicit output


A number is odd if the least significant bit is 1. By xoring the input and the input with the least significant bit as 0, we get 1 on odd numbers (0 != 1), and 0 on even (0 == 0)

# Python 2 REPL, 9 bytes

input()%2


### Sample run:

>>>input()%2
42
0


Outputs 0 for even and 1 for odd

Try it online!

# ZX Spectrum BASIC, 35 31 characters

Thanks to @Leo for removing 4 characters!

I don't know how to obtain the true (tokenized) program size, so the indicated score is in characters

1 INPUT a
2 PRINT a/2-INT(a/2)


Output is 0.5 (which is truthy) for odd input, and 0 (which is falsy) for even input.

This was tested on the Windows SpecBAS interpreter.

• Is *2 necessary? – Leo Mar 21 '17 at 21:28
• @Leo It isn't! Thanks! – Luis Mendo Mar 21 '17 at 22:34

# Taxi, 797 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 l 1 r.Pickup a passenger going to Divide and Conquer.Go to Starchild Numerology:e 1 l 1 l 1 l 2 l.2 is waiting at Starchild Numerology.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:w 1 r 3 r 1 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Trunkers.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "O"if no one is waiting.1 is waiting at Writer's Depot.Switch to plan "E".[O]0 is waiting at Writer's Depot.[E]Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.


Try it online!

Ungolfed:

Go to Post Office: west 1 left, 1 right, 1 left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: west 1 left, 1 right.
Pickup a passenger going to Divide and Conquer.
Go to Starchild Numerology: east 1 left, 1 left, 1 left, 2 left.
2 is waiting at Starchild Numerology.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: west 1 right, 3 right, 1 right, 2 right, 1 right.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1 left, 1 left, 2 left.
Pickup a passenger going to Equal's Corner.
Pickup a passenger going to Trunkers.
Go to Trunkers: south 1 left.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: west 1 left.
Switch to plan "Odd" if no one is waiting.
1 is waiting at Writer's Depot.
Switch to plan "Even".
[Odd]
0 is waiting at Writer's Depot.
[Even]
Go to Writer's Depot: north 1 left 1 right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1 right 2 right 1 left.

• Note: If this turns out to be a dupe of Engineer Toast's answer, I'll delete it, even though consensus says dupes are allowed. – Erik the Outgolfer Mar 23 '17 at 15:29
• This seems much shorter, and Taxi answers are generally similar so thats natural. – Matthew Roh Mar 23 '17 at 15:33
• @SIGSEGV Wow the Taxi website is back online. – Erik the Outgolfer Mar 23 '17 at 15:49

# Brain-Flak, 26 22 bytes

({}(())){({}[()]<>)}{}


Even: <nothing>
Odd: 1
Try it online!

({}            # Pick up the input
(())        # Push 1
)      # put the input back down

{          }   # While not 0
({}[()]  )    # Subtract 1 and...
<>     # move to the other stack (bringing the input)
{} # Pop the input (now 0)


# Scala, 14 Bytes

(x:Int)=>x%2<1


## Funciton, 68 bytes

Byte count assumes UTF-16 encoding with BOM.

╓─╖
║p║
╙┬╜┌┐
├─┤├
╔╧╗└┘
║1║
╚═╝


Try it online!

This defines a function p which takes a single integer and returns 0 for even and 1 for odd numbers.

### Explanation

╓─╖
║p║
╙┬╜


This is the function declaration header. The line leaving the box will emit the input of the function when called.

╔╧╗
║1║
╚═╝


This is a literal. The line leaving the box will emit a 1.

 ├─


This T-junction computes the bitwise NAND of its inputs, and emits it to the right.

   ┌┐
┤├
└┘


Finally, we compute the bitwise NOT, by splitting the value on first T-junction and computing the bitwise NAND with itself on the second T-junction.

The loose end on the right is used as the function's output value. Hence, the overall function computes:

p(x) = NOT(NAND(x, 1)) = AND(x, 1)


# PHP, 14 bytes

<?=$argv[1]&1;  When I test for odd or even, I only look at the first bit and not % the whole integer. # newline 19 bytes g\n0\n/\n[\nd\n]  and the number 2 # Dodos, 13 bytes  main dip dip  Try it online! This program is composed by a single main function which decrements twice its number and then recurses. Due to how Dodos works, instead of infinitely recursing the first call that would go to a negative number will return its argument instead, which will be either 0 or 1. # BitCycle, 22 bytes This program takes input on the command-line in unary; it outputs 1 for odd, nothing for even. You can also specify the -u flag and give input in decimal, in which case the output is 1 for odd, 0 for even. ?v v< < A\\B^ >/\ !  ### Explanation Here's a slightly ungolfed version in action (the same logic with extra space added for clarity): The input bits come in at the source ? and are routed into the A collector. Once the whole input is in there, bits are emitted one at a time to the right. The two splitters \\ send the first two bits downward, while the remainder go into the B collector. (Splitters deactivate after the first time a bit hits them, so the second bit passes through the deactivated first splitter and is reflected by the second one.) The second bit goes down, is reflected rightward by \, and goes off the playfield. Meanwhile, the first bit is reflected leftward by / and immediately sent rightward again by >. It passes through the two deactivated splitters and goes off the playfield. Finally, if there are any bits still in the B collector, they are now cycled around back to A. When the collectors come open, the splitters return to their original state, and the loop continues until there are less than two bits left. If the number was even, there will be no bits left, in which case the program terminates without output. If the number was odd, there is a single bit left in A. The splitters \ and / send it down and left to the >, which sends it to the right. It goes back through the deactivated / and hits the bottom-right \. The latter has not been deactivated this time because there wasn't a second bit. So it reflects the single bit downward into the sink !, which outputs it. # INTERCAL, 45 bytes DOWRITEIN:1PLEASE:1<-:1~#1DOREADOUT:1DOGIVEUP  Try it online! Prints 1 if the input is odd and 0 if the input is even. ...except this being the wonderful Compiler Language With No Pronounceable Acronym, 1 is printed as newline-I-newline while 0 is printed as underscore-newline-newline, and input has to have the individual digits spelled out in one of several natural languages or a mix thereof (such that the third test case, 16384, is just as well English ONE SIX THREE EIGHT FOUR as Basque-Latin-Georgian-Tagalog-Kwakiutl BAT SEX SAMI WALO MU). Also, I'm not actually sure which INTERCAL dialect this is. DO WRITE IN :1 Take a line of input and store the value in the variable :1. PLEASE :1<-:1~#1 Politely reassign :1 to be the first bit of its old value. DO READ OUT :1 Print :1 in "butchered Roman numerals". DO GIVE UP End the program.  # Keg, 2 3 bytes ^2%  Last number outputted will be 1 if the number is odd, and 0 if it's even Edit: Fixed for latest version Try it Online! • This seems to be for an old version, before 2019-08-13. Unfortunately the unconditional implicit input used by this code does not exist in current version. – manatwork Aug 20 at 15:52 • Fixed, don't know why that got removed – EdgyNerd Aug 20 at 15:54 • Uhm… You probably mean ^2%, thinking to multidigit numbers. – manatwork Aug 20 at 15:55 • Fixed again, oops – EdgyNerd Aug 20 at 15:58 # Cascade, 7 5 bytes #2& %  Found a 2 bytes shorter solution by abusing wrapping Try it online! # 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 – DJMcMayhem Mar 21 '17 at 20:34 # GNU sed, 7 bytes This is also a regex only solution. Input in unary is allowed for sed, based on this meta consensus. No truthy / falsy values actually exist in sed, as there are no data types. Input as unary: 7 bytes. Output is 0 for odd numbers, and nothing for even ones. s:00::g # input consists of only zeros (4 -> 0000). Two zeros are deleted as #many times as possible. Remaining pattern space is printed implicitly.  Try it online! Input as decimal: 12 bytes. Output is 1 for odd numbers, and something other than 1 for even. /[13579]$/c1     # if last char is 1, 3, 5, 7 or 9, then change pattern space to 1.
# Otherwise, do nothing. Implicit printing done at the end.


Try it online!

• You could use d instead of c1 for the decimal version. sed doesn't really have anything truthy/falsy, and the empty string matches /^\$/ so you could use that as your definition of truthy. – Riley Mar 21 '17 at 14:51
• Or you could remove the second line all together and switch c0 to c1. Then odd outputs 1 and even outputs something other than 1. – Riley Mar 21 '17 at 14:54
• @Riley I like your second idea. Initially, I used the least known sed command, =, to print 1 (as in number of input lines), but one needs the -n flag also to suppress implicit printing. – seshoumara Mar 21 '17 at 15:02

# Groovy, 7 bytes

{!it%2}


Answer too short for posting.