79
\$\begingroup\$

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

Leaderboard

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>

\$\endgroup\$
13
  • 3
    \$\begingroup\$ This isn't the first time I've confused mathematical with computational parity... this is a code site after all! \$\endgroup\$
    – Neil
    Mar 21, 2017 at 10:38
  • \$\begingroup\$ Since this is pretty much one of these(1,2,3) questions, it should probably have a snippet to see all the answers. \$\endgroup\$ Mar 21, 2017 at 13:57
  • 3
    \$\begingroup\$ @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) \$\endgroup\$ Mar 22, 2017 at 2:46
  • 4
    \$\begingroup\$ @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! \$\endgroup\$ Mar 23, 2017 at 15:09
  • 1
    \$\begingroup\$ As @HelkaHomba mentioned, zero is not positive; what is the expected result for input of zero? Or do we not care? \$\endgroup\$
    – Richard
    Mar 26, 2017 at 18:42

261 Answers 261

1
5
6
7 8 9
1
\$\begingroup\$

Scala, 15 14 5 3 bytes

_%2

Returns 0 if it's an even number and 1 if it's odd

This is equivalent to (i:Int)=>i%2.
However, this needs to be assigned to a variable of type Int=>Int, otherwise the compiler will complain.
The whole code would look like this:

val x: Int => Int = _%2
\$\endgroup\$
4
  • \$\begingroup\$ Just a tip but you can reduce this by one byte by doing <1 instead of ==0. \$\endgroup\$ Mar 25, 2017 at 14:46
  • \$\begingroup\$ I don't think that's cheating. See here. Notice that Java 8 lambda solutions often leave off the type. \$\endgroup\$ Mar 26, 2017 at 23:44
  • \$\begingroup\$ Is the <1 even needed? would it not return 0 if even and 1 if odd? \$\endgroup\$ Mar 27, 2017 at 14:49
  • \$\begingroup\$ Depends if we need a boolean, but I guess returning 0 and 1 works too. Thanks! \$\endgroup\$
    – 2xsaiko
    Mar 27, 2017 at 19:37
1
\$\begingroup\$

Swift, 18 bytes

let f={n in n%2<1}
\$\endgroup\$
1
  • \$\begingroup\$ Can be shortened to let f={n in n%2} which would return 0 for even and 1 for odd, saving 2 bytes \$\endgroup\$
    – Mr. Xcoder
    Apr 11, 2017 at 14:09
1
\$\begingroup\$

Dogescript, 32 29 bytes

such f much n
return n%2
wow

Returns 1 if n is odd, 0 otherwise.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Mar 31, 2017 at 20:44
1
\$\begingroup\$

J-uby, 5 Bytes

~:%&2

Takes the reversed-arguments version of % and partially applies 2 to it, creating a function which takes x and returns x%2. 0 for even, 1 for odd.

\$\endgroup\$
1
\$\begingroup\$

REXX 13 BYTES

say arg(1)//2

Try it here

REXX functions and instructions

\$\endgroup\$
1
\$\begingroup\$

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).

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Congratulations on being the 100th answer to this question :P \$\endgroup\$ Mar 23, 2017 at 14:19
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ Cool looking language. Welcome to the site! :) \$\endgroup\$
    – DJMcMayhem
    Jun 16, 2017 at 20:06
1
\$\begingroup\$

Common Lisp, 4 bytes

oddp

Builtin function, like Haskell odd.

\$\endgroup\$
1
\$\begingroup\$

,,,, 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
\$\endgroup\$
1
  • \$\begingroup\$ œ yeah a new solution, and a new builtin \$\endgroup\$ Jul 12, 2017 at 3:28
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Piet, 10 codels

Codel size 40

Test using this online interpreter, with codel size 40.

Does what you might expect: take input, push 2, apply the mod operation, and output the result. The program then terminates due to the J-shape at the right-hand edge.

Odd (respectively, even) input corresponds to output of 1 (respectively, 0).

Note: the lower-left-hand codel could be changed to black, white, or almost any other color without changing the program's behavior. However, if that codel is changed to "dark green" to match the codel to its right, then the program will calculate the remainder modulo 3 instead of 2.

So this program can trivially be modified to become a mod-3 calculator, with the same number of codels.

Bonus mod-3 calculator (not an answer to this challenge):

enter image description here

\$\endgroup\$
1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 30 27 bytes

	OUTPUT =REMDR(INPUT,2)
END

Try it online!

Prints 1 for odd, 0 for even.

SNOBOL doesn't have true or false and all conditions are done on SUCCESS or FAILURE so this is sort of truthy?

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 6 bytes

Add +1 for -p

#!/usr/bin/perl -p
$_%=2

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Tcl, 19 bytes

puts [expr $argv%2]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Flobnar, 6 bytes

&
%@
2

Try it online! (requires the -d flag)

I don't think it's going to get much shorter than this.

\$\endgroup\$
1
\$\begingroup\$

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).
\$\endgroup\$
1
\$\begingroup\$

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.

9 bytes, Human-readable output

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 :)

\$\endgroup\$
1
\$\begingroup\$

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).

\$\endgroup\$
1
\$\begingroup\$

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

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

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.

\$\endgroup\$
1
\$\begingroup\$

MineFriff, 7 bytes

Ii2,%o;

Explanation:

Ii` {Change the input mode to (I)nteger and take input}
2,` {Push 2 onto the stack}
%o` {x % 2 and output}
;   {end prog}
\$\endgroup\$
2
  • \$\begingroup\$ I love MineFriff from the day I find it by clicking random page (too bad it isn't a 3D language) that is, as long as it does not compete with 1+. \$\endgroup\$ Aug 18, 2020 at 14:00
  • \$\begingroup\$ @HighlyRadioactive it is 3d if used in free-form mode \$\endgroup\$
    – lyxal
    Aug 18, 2020 at 21:45
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Unless there is a way to define anonymous functions in Ruby, I believe this is a snippet, not a complete solution, unfortunately \$\endgroup\$ Oct 5, 2019 at 17:49
1
\$\begingroup\$

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

Commodore VIC-20 rulez! Donkeysoft MMXIX

\$\endgroup\$
1
\$\begingroup\$

MarioLANG, 37 bytes

;>-)+([!)
="=====#:
)![(-)-<
:#====="

Try it online!

Outputs 1 for odd and 0 for even.

\$\endgroup\$
1
\$\begingroup\$

Kotlin, 15 bytes

{n:Int->n%2<1}
\$\endgroup\$
1
\$\begingroup\$

W, 2 bytes

2m

Basically just modulo by 2...

\$\endgroup\$
1
\$\begingroup\$

Brainetry -w 2, 25 bytes

Golfed version:

a b c d e f
a b c d e f g

How it works: we set the cell size to 2 with -w 2 which pretty much does all the """heavy""" lifting for us. After that we just input one number and output it. If you want to input an actual number instead of an ASCII code point you can also set the --numeric-io flag.

The golfed version was adapted from the program at the end of this answer. To try this online you can

  • head over to this replit link, copy&paste the code into the btry/replit.btry file and hit the green "Run" button;
  • clone the github repo and from your terminal run ./brainetry btry/ppcg/even_or_odd.btry --numeric-io -w 2.
Let me read one input number
and now I will ouput its parity.
\$\endgroup\$
1
5
6
7 8 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.