# 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

# Symbolic Python, 6 bytes

_&=_/_


Try it online!

Input and output happens through the variable _ - its initial value is the input, and its final value is the output.

The code works by returning the least significant bit, performing _ &= 1. However, as 1 is obviously not allowed in Symbolic Python, _/_ is used, which is of course 1 for all inputs.

• _/_ since it's guaranteed to be positive – ASCII-only Mar 13 '19 at 6:49
• @JoKing neither does the final result? – ASCII-only Mar 27 '19 at 3:58

# Arn, 2 bytes

%2


Try it!

Returns 0 for even, 1 for odd. If you want the opposite,

!%2


would work.

# jq, 5 characters

.%2<1


Sample run:

bash-4.3$jq '.%2<1' <<< 16384 true  On-line test: • Aww, Too bad that TIO doesn't have jq. – Matthew Roh Mar 21 '17 at 11:00 # Ruby, 10 bytes ->x{x&1<1}  True for even, false for odd. • Since both 0 and 1 are truthy, returning 0 or 1 wouldn't be allowed for ruby, right? – Eric Duminil Mar 22 '17 at 21:50 • Also, are methods allowed for golf submission, or should they all look like functions : would odd? or even? be a correct submission? – Eric Duminil Mar 22 '17 at 21:53 • @EricDuminil Correct; in ruby 0 and 1 are both truthy. – Christopher Lates Mar 23 '17 at 20:11 # Haskell, 8 bytes (mod2)  1 for odd and 0 for even Test cases: >(mod2)1 1 >(mod2)2 0 >(mod2)999999 1  ## Alternative with True/False output, 13 bytes (==0).(mod2)  Test cases with repl usage: >((<1).(mod2))1 False >((<1).(mod2))2 True >((<1).(mod2))16438 True >((<1).(mod2))999999 False  • Um odd is a Prelude Haskell function. – Ørjan Johansen Mar 21 '17 at 15:39 # 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 # SQLite, 10 bytes SELECT x%2  Try it online! # Groovy, 7 bytes {!it%2}  Answer too short for posting. # Forth, 11 bytes : f 2 mod ;  Try it online Output is 0 if even, 1 if odd. ## Jelly, 2 bytes Here's an alternate approach to this Jelly answer by ais523 BṪ B convert the input to binary Ṫ and return its last character: 0 for even, 1 for odd.  Try it online! Also at 2 bytes, the classical Modulo 2: %2  Try it online! which also returns 0/1 for even/odd resp. # 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! ## Scratch, 4 blocks + 1 byte Python equivalent: i = input() print(i % 2)  Returns 0 for even and 1 for odd. # 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) # Campfire, 8 bytes Prints 1 for odd input or 0 for even input, then exits with an error. &2&2%.%.  Campfire is an esoteric programming language I've created a couple of months ago. While it has a builtin for computing remainders, its unique flow of instructions makes even this simple challenge not so trivial (even if in this case the source turns out to be quite symmetric and nice). In Campfire, after executing each instruction, the instruction pointer jumps to just after the next occurrence of the instruction just executed (wrapping between the end and the start of the code). Moreover, if the value on the top of the main stack is not 0, the instruction pointer is turned around before jumping (when backwards, it jumps to just before the previous occurrence of the executed instruction). Here's an explanation of the execution of this program. * marks the instruction executed at each step, and <,>, or ? marks the spot where the instruction pointer will jump to, along with its direction. &2&2%.%. * < & takes a number from input and pushes it to the stack. Since we're dealing only with strictly positive numbers, we will always switch direction. * > Push 2 to the stack (then switch direction) * ? Compute remainder. If the result is 1 we will switch direction, if it's 0 we won't. #First alternative: &2&2%.%. * < Output the result, the stack is now empty, and an empty stack has impicit 0s on it, so we won't switch direction. * Try to compute remainder, but the stack is composed only by implicit 0s, so this will exit the program with an error. #Second alternative: &2&2%.%. > * We execute the other output instruction, result is the same. * Again, we end by computing 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 # TI-Basic, 4 bytes fPart(Ans/2  Other solutions: remainder(Ans,2 5 bytes - returns 0 even 1 odd  Returns 0 for even numbers and 1/2 for odd numbers. These values evaluate to false and true respectively in TI-Basic. # C, 11 bytes f(n){n&=1;}  Because, why not. Returns false (0) for even, true (1) for odd. Works with gcc on linux/x86. • Huh. Looks okay. – Matthew Roh Mar 23 '17 at 9:49 # 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 # Vim Macro 54 Bytes ^vehxiF^[ve"nyo1234567890^MFTFTFTFTFT^[k@njvyo^[pi^[k$vggx


This Vim Macro works on any file that contains just an integer. During the cleanup process, it removes all the code above itself. This can probably be better implemented where it cleans up only the code it wrote but that would require more bytes.

The ^[ is escape (return to normal mode) and the ^M is the enter key.

What this basically does is it removes everything but the last digit of the number, prepends F to it, saves that into register n so now register n holds F<your number>. Then, it creates two new lines. One containing 1234567890 and the other line containing FTFTFTFTFT. Once it creates the second line, the cursor moves up, executes the n macro, thus finding backwards the first occurrence of <your number>, going down one line to the second line, yanking the corresponding true or false character from it, creating a new line, pasting that character, and then deleting everything it just did.

Vim Macros present a really interesting challenge and require you to think in a different way than what you're used to. It was super cool to work on this.

# Scala, 14 Bytes

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


<?=$argv[1]&1;  When I test for odd or even, I only look at the first bit and not % the whole integer. # Klein, 1817 16 + 3 bytes, (non-competing) Uses the 001 topology. Embedded in a Klein Bottle 1(/+@ -+)-($?/:1


## Explanation

Here is a gif of it running on 6:

The general way this works is it continually decrements the input down to zero each time multiplying a saved value by -1. That way the saved value will be negative if odd and positive if even.

### Setup

Right as the program begins running it does its set up

1(


This puts a 1 on the scope. This is the number we will multiply by -1 to keep track of the parity.

We then use a mirror to deflect the ip of the top of the screen. Since we are on a Klein Bottle and not a Torus this deflection will not only bring us to the bottom but also flip our horizontal coordinate. The ip will move upwards through mostly blank space until it hits another mirror. This mirror puts it in the main loop.

### Main Loop

In the main loop we make a duplicate of the input and decrement it by one, multiply the scoped value by -1 using )-( and then we switch the copied version of the counter with the original, we copied it earlier because ? our conditional jump consumes a value. Since ? skips the mirror we will run until our counter is zero.

However since we are checking the copy of the counter, we will actually exit when we hit -1. This is important because it saves us from having to make a value later.

### Cleanup

Once we hit zero we are deflected again but the mirror. This sends us over the top of the screen. Since we are on a Klein Bottle this twists us back around and causes the ip to collide with the ) used in part of the code. This is convenient because it recalls the scoped value to the stack. We then get deflected by one of the mirrors from before. Lastly we add the two values, the counter and the saved value. The counter will always be -1 so we are essentially just subtracting 1 from the saved value. The saved value will be either 1 or -1 so our result is either -2 or 0. Then we end and output using @.

# newline 19 bytes

g\n0\n/\n[\nd\n]


and the number 2

# 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

# 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

• Uhm… You probably mean ^2%, thinking to multidigit numbers. – manatwork Aug 20 '19 at 15:55
• 2% works again now. – Lyxal Nov 15 '19 at 21:33