# 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

## 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. – Dennis Mar 26 '17 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. – Dennis Mar 26 '17 at 16:08
• Welcome to PPCG! – Pavel Mar 26 '17 at 19:40
• @ГригорийПерельман thank you – Aashutosh Rathi Mar 28 '17 at 7:33
• @Dennis thanks for edit 👍 – Aashutosh Rathi Mar 28 '17 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&| – Adám May 8 '17 at 8:55

# Acc!!, 43 bytes

N
Count i while _/10 {
N-_%2*2
}
Write _+41


Because of quirks of the input mechanism in Acc!!, the input number (given on stdin) has to be terminated with a signal value--in this case, a tab character. The code outputs 2 if the number is even, 0 if it is odd.

### Explanation

# Read a character's ASCII value into the accumulator
N
# Loop while accumulator intdiv 10 is greater than 0 (i.e. acc >= 10)
Count i while _/10 {
# Read another ASCII value, subtract (current acc % 2) * 2, and store back to acc
N-_%2*2
}
# At the end of the loop, we know we just read a tab character (ASCII 9). This means the
# acc value is 9 if the previous digit had an even ASCII value, or 7 if it was odd. We
# add 41 to convert to the ASCII codes of 2 and 0, respectively, and write to stdout.
Write _+41


# Scala, 9 bytes

(_:Int)%2


This outputs 1 for odd, 0 for even

# Clojure, 15 bytes

#(= 0(rem % 2))


Ignoring the obvious built-ins, this is probably as short as it gets.

Checks if the argument divided by 2 equals 0. Nothing fancy. Returns true for even numbers, false for odd.

Beaten by brainfuck!

# Dogescript, 32 29 bytes

such f much n
return n%2
wow


Returns 1 if n is odd, 0 otherwise.

• You could still keep the Dogescript syntax and save 3 bytes: such f much n return n%2 wow. There's no need to convert a truthy value to boolean. – Grant Miller Mar 31 '17 at 20:44

# Aceto, 6 bytes, non-competing

(Non-competing because the question predates the language.)

%2
rip


ri reads a string and casts it to an integer, 2% does modulo 2, and p prints. 0 stands for even and 1 for odd in the printed result.

• This is very likely the theoretical minimum. – L3viathan May 8 '17 at 8:31
• rip Aceto, postdated the challenge – Matthew Roh May 8 '17 at 8:32
• :) @L3viathan is indeed the theoretical minimum. – Laura Bostan May 8 '17 at 8:33

# REXX 13 BYTES

say arg(1)//2


Try it here

REXX functions and instructions

# Actually, 2 bytes

1&


Try it online!

Output is 0 if even, 1 if odd. The code is very straightforward: bitwise-AND (&) with 1 (return low bit of input).

# braingasm, 3 bytes

Takes input from stdin, prints 0 for even and 1 for odd.

;o:


; reads an integer, o checks the "oddity" (opposite of parity), : prints an integer.

edit: changed to p to o to retrofit to a breaking change in the language.

• Congratulations on being the 100th answer to this question :P – math junkie Mar 23 '17 at 14:19

# WC, 40 bytes

WIP mini language I created.

;>_0|;>(?#@8|!@3|//##@2|!@2|//#$-$-/)*$ Explanation: ;>_0| New var using the first artifact (the input number) ;>( Start a new function ? Select the first variable (reset var index) #@8| Start if statement with 9th global ("-1") as condition !@3| Print the 4th global ("1") // Terminate program # End if statement #@2| Start if statement with 3rd global ("0") as condition !@2| Print the 3rd global ("0") // Terminate program # End if statement$-$- Decrement the current variable twice / Restart context (the current function) ) End function *$             Call the current variable (the function)


Try it online!

• Cool looking language. Welcome to the site! :) – James Jun 16 '17 at 20:06

# ,,,, 1 byte

œ


Yeah, yeah, a builtin... For anybody wondering about the choice of character, it's supposed to be odd or even or o or e.

However, I do have other solutions.

## 2 bytes

1&


### Explanation

1&

implicit input
1   push 1
&  pop input and 1 and push input & 1 (bitwise AND)
implicit output


## 2 bytes

2%


### Explanation

2%

implicit input
2   push 2
%  pop input and 2 and push input % 2 (modulo)
implicit output

• œ yeah a new solution, and a new builtin – Matthew Roh Jul 12 '17 at 3:28

# x86_64 Linux machine language, 5 bytes

0:       97                      xchg   %edi,%eax
1:       83 e0 01                and    $0x1,%eax 4: c3 retq  To try it, compile and run the following C program #include<stdio.h> const char f[]="\x97\x83\xe0\1\xc3"; int main(){ for( int i = 0; i < 10; i++ ) { printf("%d %d\n", i, ((int(*)(int))f)(i) ); } }  Try it online! # Aceto, 5 bytes ri2%p  r reads input i converts to integer 2% takes the number modulo 2 p prints the answer  Try it online! # Underload, 5 bytes ():aS  Underload doesn't really have a concept of Truthy/Falsey, so this is empty/nonempty output for odd/even respectively. Input should be in unary (as some number of ~) between the a and the S. ## Explanation () pushes the empty string. : duplicates it and () wraps the top stack element in parenthesis, meaning the stack now looks like "", "()". The input now appears in the program, meaning it is executed as code. ~ is the swap instruction in Underload, meaning that an even input is an even number of swaps, which doesn't affect the stack, and an odd input is an odd number of swaps, which has the same effect as a single swap. S outputs the top stack element, which will be either () if the input was even, and if the output was odd. I mentioned that Underload doesn't have Truthy/Falsey, but the common way to represent booleans as Underload code that either swaps or doesn't swap, meaning that the cheaty one-byte program S technically works as a valid submission. # Pyt, 2 bytes 2%  Explanation  Implicit input 2% Mod 2 Implicit print  Odd is truthy, even is falsy Try it online! Alternatively, also 2 bytes 2|  Explanation:  Implicit input 2| Is it divisible by 2? Implicit output  Even is truthy, odd is falsy Try it online! # 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 # Python 2, 13 bytes lambda n:~n&1  Try it online! No shorter than the other non-REPL Python answers, but uses slightly different logic. Takes the bitwise complement of the input number (-x-1) and performs a BITWISE AND on it. Returns 1 if the complement is odd, and 0 if the complement is even - and therefore returns 1/0 if the original number was even/odd. (Could be shortened by 1 byte by removing the complement ~ if 0=True and 1=False is allowable.) # Flobnar, 6 bytes & %@ 2  Try it online! (requires the -d flag) I don't think it's going to get much shorter than this. ## CHIP-8 assembly, 22 bytes 0x6001 F10A 410F 120C 8210 1202 8226 8F03 FF29 D005 1214  Takes in a number entered by the user, until it is terminated by the user pressing the F key, and prints out to the screen 0 if it's odd, or 1 if it's even. The CHIP-8 had 16 8-bit registries (V0 to VF), with VF mostly being used for carry operations. The ROM was loaded into memory at address 0x200, which is why the jump operations are offset. It also contained display-representations of the numbers 0-9 and letters A-F in memory at 0x00, so that a programmer need not create them. The code works like this: 0x200: 60 01 Set V0 to 0x01. 0x202: F1 0A Wait for a key to be pressed, and enters the value into V1. 0x204: 41 0F Skip the next instruction if V1 does not equal 0x0F. 0x206: 12 0C Jump to instruction address 0x20C. 0x208: 82 10 Assign the value of V1 into V2. 0x20A: 12 02 Jump to instruction address 0x202. 0x20C: 82 26 Store the least significant bit of V2 into VF, left-shift V2 by one bit, and store the shifted value into V2. 0x20E: 8F 03 Set VF to VF XOR V0 (V0 is set previously to 1, so this is equivalent to NOT VF). 0x210: FF 29 Set the memory address pointer (I) to the character representation of the value in VF. 0x212: D0 05 Draw the data from the address pointer I to the screen, at pixel (0, 0), with a width of 5 pixels (the height is always 8 pixels). 0x214: 12 14 Jump to instruction address 0x214 (i.e., loop indefinitely).  # Z80Golf, 9 8 bytes 00000000: d5d2 0380 e601 ff76 .......v  Try it online! ### Disassembly start: push de jp nc,$8003
and 1
rst $38 halt  Golfed a byte using the "input loop at start" pattern:  push de ; Push 00 00 (return address) to the stack jp nc,$8003 ; Escape the loop if carry is set (EOF)
; otherwise take next input and return to the start of the program


## Previous solution, 9 bytes

00000000: cd03 8030 fbe6 01ff 76                   ...0....v


Try it online!

### Disassembly

start:
call $8003 jr nc, start and 1 rst$38
halt


Accepts the decimal input (binary, octal, hexadecimal, or any other even base would work), and outputs ASCII 0 for even, 1 for odd.

call $8003 calls getchar, which stores the next char to register a, or sets the carry flag on EOF. Since the only significant data is the last char, the program simply calls getchar repeatedly until EOF. and 1 takes the parity, rst$38 is a golf idiom for call putchar, and halt terminates the program.

00000000: cd03 8030 fbe6 31ff 76                   ...0....v


Try it online!

Limiting the input to decimal or lower even bases, we can get more readable result ('0' = $30 and '1' =$31) by changing and 1 into and $31. Also works for hexadecimal if you use 0123456789pqrstu, case sensitive :) # Little Man Computer, 31 bytes, 5 instructions INP SUB 5 BRP 1 ADD 5 OUT DAT 2  Which boils down to this once assembled into RAM: 901 205 801 105 902 002  Outputs $$\ 1 \$$ for an odd number and $$\ 0 \$$ for an even number. A online emulator can be found here, though you may need to increase the speed to avoid waiting a painfully long time (if anyone finds a better online version, please enlighten me). # Regex (ECMAScript), 7 bytes ^(xx)*$

Try it online!

The input is in unary, as the length of a string of xs. It matches even numbers and returns "no match" for odd numbers.

This works in all regex flavors, even formal regular expressions, which lack some ECMAScript regex features (backreferences and lookaheads).

There is no shorter (6 bytes or less) unary ECMAScript regex function (with nonnegative integer input and match/no-match output) that requires the (, ), *, or + symbols.

# Alchemist, 79 35 bytes

-43 bytes thanks to ASCII-only!!

-1 byte thanks to Jo King!

_->s+In_i
e+i->
0e+i->e
s+0i->Out_e


Outputs 0 for even and 1 for odd, try it online!

## Ungolfed

• You could probably golf the outputs to... 0 and 1 or "" and "1" or something – ASCII-only Jan 29 '19 at 8:05
• 56? – ASCII-only Jan 29 '19 at 8:07
• if other outputs (0/1 for odd/even) are allowed, 36 – ASCII-only Jan 29 '19 at 8:10
• @ASCII-only That doesn't work since the output can occur before the input. 35 bytes should work deterministically – Jo King Mar 13 '19 at 6:43

# Come Here, 68 bytes

ASKi0CALLi*256iCOME FROM SGN(i//256)1CALL(i//256)iTELL48+(iMOD2)NEXT


Less golfed:

ASK i
0 CALL i*256 i
COME FROM SGN(i//256)
1 CALL (i//256) i
TELL 48 + (i MOD 2) NEXT


COME HERE uses integers internally, but handles input and output as strings; unfortunately, the string encoding it uses really isn't all that helpful for working with input as numbers. In this case, we have to repeatedly divide by 256 until we get a value that is less than 256, in order to get the last character.

If little-endian (rather than big-endian) input is allowed, we can use this shorter version (22 bytes) instead:

ASKiTELL48+(iMOD2)NEXT


Prints 0 for even, and 1 for odd.

# ZX80 (4K ROM) 23 tokenised BASIC bytes

 1 INPUT A
2 PRINT A;":"; NOT A AND 1
3 CONTINUE


This is a very simple solution as in Sinclair ZX80 BASIC, PRINT 111 AND 1 will produce 1 (and therefore any odd number entered will produce 1 because in binary for any odd positive integer the zeroth bit is always set, so PRINT 11 AND 1 will do 00001011 & 00000001 at the processor level more or less) - if we assume even is true then we can use NOT to invert the value, therefor NOT 111 AND 1 will produce 0 or our false value.

Using the CONTINUE command will continue the symbolic listing from line 1. You may also use RUN but both are equal in the basic tokens used.

## ZX80 (4K ROM) 16 tokenised BASIC bytes

If we assume that odd is our true value then we can remove some of the logic as follows (also saving bytes):

 1 INPUT A
2 PRINT A;":";A AND 1
3 RUN


There is one caveat; by using ZX80 BASIC, you may only enter 16-bit wide signed integers, so the range is -32768 to +32767 inclusive.

The same logic will work in Commodore BASIC (C64/VIC-20) so whilst both of the above will work, you may condense it into one line like 0inputa:printa":"aand1:goto.

# Pyramid Scheme, 221 bytes

    ^        ^ ^
/ \      /l\-
/set\    /oop\
^-----^  ^-----^
-    ^- /*\   / \
^- ^---^ /set\
/#\ -^  -^-----^
^--- /-\  -    /-\
/l\  ^---^     ^---^
/ine\/1\  -     -  /2\
--------           ---


Try it online!

Outputs 0 for even and 1 for odd.

Pyramid Scheme has no modulus, no integer division, and no bitwise operators. The best approach I could conceive was repeatedly subtracting two from the input until either it or its predecessor is zero, then printing the final value.

This program translates rather easily to true Scheme. I have to say, that's my favorite part of this language—it's very nearly a Scheme dialect in its own right, despite being a joke!

(define n (read))
(do ()
((= 0 (* n (- 1 n))))
(set! n (- n 2)))
(display n)


Try it online!

# Re:direction, 7 bytes

♦♦
▼►
◄


Outputs 1 if odd, and 0 if even. Basically works by alternating between the left and right side until a ▼ is found (▼ is at the end of the input) and then outputs depending on which side it is on.

Try it online!

# Ruby, 6 bytes

n.odd?


Try it online!

I don't know if this is cheating. There's a method definition in the header. Is there a way to skip doing this and pass in a number differently, perhaps?

odd? is a default operation in Ruby.

• Unless there is a way to define anonymous functions in Ruby, I believe this is a snippet, not a complete solution, unfortunately – caird coinheringaahing Oct 5 '19 at 17:49

# Commodore BASIC (C64/128, VIC-20, TheC64/Mini, C16/+4) - 21 tokenized bytes

In this one, odd numbers produce a TRUE value and even numbers produce a FALSE (though on Commodore BASIC, FALSE is zero and TRUE is negative one; it does not do this, more conforms to modern-days TRUE/FALSE integer equivalents)

 0 inputa:ifatH?a":"aaN1


Expanded and non-minimised as:

 0 input a
1 if a then print a; ":"; a and 1