# 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

## Alice, 7 bytes

1\@
oAi


Try it online!

Prints 0 for even inputs and 1 for odd inputs.

### Explanation

This is structurally similar to my addition program, but the flipped mirror subtly changes the control flow:

1    Push 1.
\    Reflect northeast. Switch to Ordinal.
Bounce off the boundary, move southeast.
i    Read all input as a string.
Bounce off the corner, move back northwest.
\    Reflect south. Switch to Cardinal.
A    Implicitly convert input string to integer. Compute bitwise AND with 1.
Wrap around to the first line.
\    Reflect northwes. Switch to Ordinal.
Bounce off the boundary, move southwest.
o    Implicitly convert result to string and print it.
Bounce off the corner, move back northeast.
\    Reflect east. Switch to Cardinal.
@    Terminate the program.


## Labyrinth, 5 bytes

?_2%!


Prints 0 for even and 1 for odd inputs.

Try it online!

?   Read input.
_2  Push 2.
%   Modulo.
!   Print.


Now the instruction pointer hits a dead end and turns around. Upon attempting the % on an empty stack, the program exits due to division by zero.

## alternatively, also 5 bytes

?#&!@


Try it online!

?   Read input.
#   Push stack depth (1).
&   Bitwise AND (extract least-significant bit).
!   Print.
@   Terminate.

• Would #?#%! or _?#%! work too? – MildlyMilquetoast Mar 21 '17 at 17:09
• @MistahFiggins yes. – Martin Ender Mar 21 '17 at 17:10

# Octave, 12 bytes

@(x)mod(x,2)


Takes x modulus 2. Returns 0 for even numbers and 1 for odd numbers. These evaluates to false and true respectively in Octave. This works in MATLAB too.

## Hexagony, 7 bytes

?{2\%'!


Prints 0 for even numbers (falsy) and 1 for odd numbers (truthy).

Try it online!

### Explanation

Here is the folded code:

 ? {
2 \ %
' !


I believe this is optimal although not unique. As usual I've run a brute force search (not an exhaustive one, but the characters I've excluded are very unlikely to be useful for this program). It did find a whole bunch of other solutions, which I haven't investigated in detail yet:

^?"2^%!
^?"2}%!
{?"2^%!
{?"2}%!
2^?\%"!
2}?\%"!
\{?2%'!
2^?")%!
2^?"1%!
2^?"2%!
2^?=^%!
2{?"}%!
2{?'=%!
2{?={%!
2}?")%!
2}?"1%!
2}?"2%!
2}?=^%!
|"?^2%!
)>"?}!%
\}2?%"!
2^=?^%!
2{'?^%!
2{=?{%!
2}=?^%!


As for the solution I've picked above:

?   Read input.
{   Move to the left memory edge.
The IP wraps around to the left corner.
2   Set the memory edge to 2.
\   Deflect the IP southwest.
'   Move to the memory edge that points at the input and at the 2.
The IP wraps around to the right corner.
%   Take the input modulo 2.
!   Print the result.
The IP wraps to the top right corner.
{   Move to the input edge, which points at two empty edges.
%   Attempt to take the modulo of those, which terminates the program
due to the attempted division by zero.


I did look at the next program the above list, which is quite fun because it loops through the first two lines 6 times, filling an entire hexagonal ring with 2s before wrapping back around to the first and taking the modulo. At that point it actually uses the second 2 for the computation. I'm sure there are some gems in the others as well, but I don't think I'll have the time to go through them in detail.

# Cubix, 6 bytes

OI2%/@


This outputs 1 for odd numbers, and 0 for even. Try it here!

# Explanation

First, the cube form.

  O
I 2 % /
@


The following instructions are executed:

I2%O2@ # Explanation
I      # Take input
2%    #   Modulo 2
O   #   Output
2  # Push 2 to the stack
@ # End the program


# Pure Bash, 8

• 3 bytes saved thanks to @Dennis
(($1%2))  Input given as a command-line parameter to this function f. Output returned as a shell return value - display with echo$?

## QBasic 4.5, 16 15 bytes

INPUT a
?1AND a


One byte saved by @DLosc!

This shows a 1 for odd numbers and a 0 for even.

• Save one byte by using bitwise operators: 1AND a is equivalent to a MOD 2. – DLosc Mar 22 '17 at 4:42

odd


It's built-in. Works as expected. There is also even but of course that's one byte longer.

# Perl 5, 6 bytes

5 bytes of code + -p flag.

$_%=2  Try it online! # Clojure, 4 bytes odd?  A function which checks if its argument is odd. Example usage: (odd? 3). Clojure does also have even? function. # Ohm, 2 bytes è  Explanation: è: (pop()%2)==1 Ohm also has implict input and output  # Sesos, 2 bytes SASM set numin get jmp, sub 2  SBIN 00000000: 1228 .(  Output is via exit code, zero for even and non-zero for odd. Odd inputs may take a long time. Try it online! ### How it works This is a bit cheaty, but it complies with our rules. The program reads a decimal integer from STDIN and keeps subtracting 2 until it reaches 0. For even inputs, this finishes in linear time and does nothing, successfully. Programs that do not contain the set mask directive use arbitrary precision integers, so odd inputs will slowly continue to allocate memory. Once the available memory is exhausted, the program will get killed, resulting in a non-zero exit code. Don't expect this to happen anytime soon... ## Alternate version, 3 bytes ### SASM set numin get jmp, sub 2  ### SBIN 00000000: 124601 .F.  Output is via exit code, zero for even and non-zero for odd. Stray output to STDOUT should be ignored. Try it online! ### How it works Marginally less cheaty. The program works as before, but also prints the tape cell as a character in each iteration. This will exit with an error once the cell becomes negative. # PowerShell, 9 bytes "$args"%2


Try it online!

Ho-hum. Takes input $args and stringifies it, because there can be an implicit cast from string to int, but not from array to int. Then runs that through modulo 2. Outputs 0 (a falsey value) for even and 1 (a truthy value) for odd. • $arghhh, I scrolled through all the answers, didn't see PowerShell, then opened TIO and put this exact answer in. When I ran it and saw a cache hit, I was like "uh oh" and then found this. Don't know how I missed it haha. Funny that we used the exact same argument as well otherwise I mightn't have noticed! – briantist Mar 21 '17 at 18:40
• You beat me to it! – root Jul 9 '17 at 2:55

# PHP, 12 bytes

echo$argn&1;  Run like this: echo 123 | php -R 'echo$argn&1;';echo

• Odd: 1
• Even: 0

## Rail, 29 bytes

$'main' oi r e | >{main} \2-  Try it online! ### Explanation Every time I try to golf something in Rail, I remember how incredibly tricky it is, because of how strict the track placement rules are (especially for junctions). I think this is the first time, that I actually used recursion (or any method calls at all). Rail programs start from the $, going southeast. i reads a character from STDIN. e checks for EOF. > is a three-way junction. It pops the result from the EOF check. If we haven't reached EOF yet, the train takes the left-turn. {main} is a recusive call to the main routine, which really just means that we'll start over from the beginning.

Once we've reached EOF, the train will take the right-turn at the junction. The -, \ and | on the remainder of the track are necessary to make the train take a couple of turns. 2 pushes 2, r computes the last digit modulo 2 (r for "remainder") and o outputs it. Technically, we'd have to terminate the track with #, but I ran out of space and the program exits either way, sadly, crashing the train.

This version of the trolley problem (do I save the trolley or do I save the bytes) seems to be more easily resolved than the classical one...

$'main' |/i- | >2ro \-e/  Try it online! This one uses a physical loop in the tracks. The basic idea is the same: the track initially leads to the EOF-check e, after which we reach the 3-way junciton. As long as there is input left to reach, we read one character with i and loop back into the previous track. Once we reach EOF we compute and print the parity with 2ro. Obviously, we still can't afford the extra byte to prevent the train from derailing. ## R, 1210 9 bytes scan()%%2  Outuputs 1 for TRUE or 0 for FALSE when input in even or odd (respectively) 0 is supported. -2 bytes thanks to @plannapus -1 byte thanks to @user2390246 • If I may: !scan()%%2. – plannapus Mar 21 '17 at 14:26 • Don't 1 and 0 count as truthy and falsy in R? (They pass the "if" test). In which case you could just go with scan()%%2. – user2390246 Mar 21 '17 at 16:11 # K (oK), 2 bytes 2!  Try it online! # Lua, 20 bytes print(io.read()%2<1)  This returns true if STDIN mod 2 is 0 and returns false if it isn't. You can also remove the <0 to get the opposite results. • You can change ==0 to <1. – Pavel Mar 26 '17 at 19:41 # OIL, 39 bytes 5 0 9 0 10 0 1 16 9 9 0 10 0 1 17 2 4 4  ## Explanation: 5 0 reads the input into line 0. 9 0 decrements line 0 (using the fact that the input must be positive (i.e. >0)). 10 0 1 compares line 0 to line 1 (which contains a 0). If they're identical, that means the number must have been odd, jump to cell 16. 9 0 decrements line 0 again. 10 0 1 does the same comparison again, except this time equality means the number was even, jump to cell 17. Otherwise go on with the decrementation process (jump to line 2). Line 16 and 17 both contain a 4 (print), meaning if we jumped to line 16, 4 4 will print what's in line 4 (10). If we jumped to line 17 instead, 4 (0) will print 0, the value in line 0. # TI-Basic-83, 4 bytes fPart(.5Ans  Gets the partial fraction part of 1/2 multipled by Ans, returns 0 if even, anything else if odd. • It's 11 bytes m8! – Daniel W. Jul 10 '17 at 7:50 • @DanFromGermany Ti-Basic is a tokenized language. – pizzapants184 Jul 11 '17 at 3:05 # Neim, 1 byte ᛄ  Try it online! Explanation: ᛄ: modulo 2 (implicit input and output)  # Python, 12 bytes lambda x:x%2  use with g = lambda x:x%2 g(a)  where a is the input number. Returns 1 for Odd, and 0 for Even. # Symbolic Python, 7 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 evaluates to True and acts exactly like 1. • _/_ since it's guaranteed to be positive – ASCII-only Mar 13 at 6:49 • _/_ doesn't evaluate to True anymore – Jo King Mar 15 at 10:59 • @JoKing neither does the final result? – ASCII-only Mar 27 at 3:58 • Err, I didn't mean the solution was invalid, just the explanation had a leftover "_/_ evaluates to True" part. – Jo King Mar 27 at 5:24 # Intel 8080 machine code, 1 byte 1F RAR ; rotate accumulator's least significant bit into Carry Flag  Input is in A, result is CF=1 if odd, CF=0 if even. Here is a test program for the MITS Altair 8800 that will take the input number and display the result (odd or even) on the front panel lights. Just follow these programming instructions on the front panel switches: Step Switches 0-7 Control Switch Instruction Comment 1 RESET 2 00 111 110 DEPOSIT MVI A, 27 Load number to examine into A 3 00 011 011 DEPOSIT NEXT Set value to test (27 in this case) 4 00 011 111 DEPOSIT NEXT RAR Rotate A's LSB into CF 5 11 110 101 DEPOSIT NEXT PUSH PSW Push Status Flags to stack 6 11 000 001 DEPOSIT NEXT POP B Pop Status Flags to BC register 7 00 111 110 DEPOSIT NEXT MVI A, 1 CF is LSB (0x1) of Status Flags 8 00 000 001 DEPOSIT NEXT 9 10 100 001 DEPOSIT NEXT ANA C Mask CF so is only result displayed 10 11 010 011 DEPOSIT NEXT OUT 255 display contents of A on data panel 11 11 111 111 DEPOSIT NEXT 12 01 110 110 DEPOSIT NEXT HLT Halt CPU 13 RESET Reset program counter to beginning 14 RUN 15 STOP D0 light will be on if value is odd, or off if even  If entered correctly, the program in RAM will look like: 0000 3e 1b 1f f5 c1 3e 01 a1 d3 ff 76 To re-run with a another number: Step Switches 0-7 Control Switch Comment 1 RESET 2 00 000 001 EXAMINE Select memory address containing value 3 00 000 010 DEPOSIT Enter new value in binary (2 in this case) 4 RESET 5 RUN 6 STOP  Try it online! Just follow the easy steps above! Output Input = 27, light D0 is ON indicating ODD result: Input = 2, light D0 is OFF indicating EVEN result: # 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

(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

# PHP, 14 bytes

<?=\$argv[1]%2;


Try it online!

Outputs 1 for odd, 0 for even.

# SQLite, 10 bytes

SELECT x%2


Try it online!

# Forth, 11 bytes

: f 2 mod ;


Try it online

Output is 0 if even, 1 if odd.