81
\$\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
    Commented 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\$ Commented Mar 21, 2017 at 13:57
  • 3
    \$\begingroup\$ @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) \$\endgroup\$ Commented 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\$ Commented 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
    Commented Mar 26, 2017 at 18:42

264 Answers 264

1
3 4
5
6 7
9
1
\$\begingroup\$

Brachylog, 3 bytes

%₂0

Try it online!

Explanation

Well…

%₂0     Input mod 2 = 0
\$\endgroup\$
1
\$\begingroup\$

Cardinal, 7 bytes

%++~:M.

Outputs truthy if odd falsy if even

Try it online!

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

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.

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

C, 15 bytes

#define f(n)n&1

Returns 0 if even, 1 if odd.

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

Common Lisp, 7 Bytes

#'evenp

Built-in function that checks parity. Barely beating Java!

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

><>, 4 + 3 = 7 bytes

Outputs 1 for odd and 0 for even. Execute using -v (+ 3 bytes).

2%n;

Try it online!

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

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

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

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

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.

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

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

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

V, 8 7 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 ò
\$\endgroup\$
1
  • \$\begingroup\$ Cool approach, I like it! Alternate (but very similar) approach: Àé1Ó11 \$\endgroup\$
    – DJMcMayhem
    Commented Mar 21, 2017 at 20:34
1
\$\begingroup\$

J, 3 bytes

2&|

Explanation:

2&|
  |    this does mod, only with the order of the operands reversed
2      the number 2... derp
 &     attaches 2 to | so it can be the left operand
       the right operand is implied due to tacit programming
\$\endgroup\$
4
  • \$\begingroup\$ Alternatively, 2|]. \$\endgroup\$ Commented Mar 21, 2017 at 18:37
  • \$\begingroup\$ um... what does the ']' do? \$\endgroup\$
    – Bijan
    Commented Mar 21, 2017 at 18:51
  • \$\begingroup\$ Well, it means "yield right argument", and is often the identity function. A train of three verbs (or a constant followed by two verbs, as in this case) constitutes a "fork", in which the middle "tine" of the verb (in this case, %) is applied the result of the application on each of the outer tines. If a constant is invoked in this way, it simply returns the constant. So, for an argument y, (2|])y is equivalent to (2 | (] y)), which is 2 | y. \$\endgroup\$ Commented Mar 21, 2017 at 19:24
  • \$\begingroup\$ An APL expression for all the 3-byte J expressions that are valid answers \$\endgroup\$
    – Adám
    Commented Mar 23, 2017 at 10:59
1
\$\begingroup\$

Bash + coreutils, 11 bytes

Output is 1 for odd numbers, and nothing for even ones. This is a full program. There is another bash answer by Digital Trauma, but that one is a function, however it is in pure bash.

seq $[$1%2]          # give 'input % 2' as argument to seq. Notice that 'seq 0'
                     #doesn't print anything.

Try it online!

I use seq, because it is 1 byte shorter than echo, but it has a different truthy / falsy mapping.

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

tinylisp, 18 bytes

There's a library function for that.

(load library)odd?

The function itself is odd?--call it like (odd? 12). Try it online!

Writing a function from scratch is 28 bytes (TIO):

(d o(q((n)(i(l n 2)n(o(s n 2

This defines o as: if n is less than 2, return n, else recurse with n-2.

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

LibreLogo, 19 bytes

Code:

print int input "%2

Result:

Returns 0 for even numbers, and 1 for odd numbers.

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

Pip, 3 bytes

a%2

Try it online!

Explanation:

a   is auto-read from the command line
%2  Modulo 2 --> yields a 0 for even, 1 for odd
    The result of the last statement is auto-printed.
\$\endgroup\$
1
\$\begingroup\$

Jellyfish, 6 bytes

p|i
 2

Try it online!

Print (p) the input (i) modulo (|) two (2).

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

Carrot, 5 bytes

#^F%2

Try it online!

Note: this is a trivial answer. Please do not vote. I am only posting this for completion.

Explanation

#^                // set the stack to the input
  F               // convert it to a float
   %2             // take the modulo 2 of it
                  // implicit output
\$\endgroup\$
4
  • \$\begingroup\$ That's okay. Every answer else is trivial too. At least it's not a builtin. \$\endgroup\$ Commented Mar 23, 2017 at 9:32
  • \$\begingroup\$ Why do you have to convert to float? \$\endgroup\$ Commented Nov 14, 2019 at 16:27
  • \$\begingroup\$ @HelloGoodbye Because it is by default a string, although yes, I should work just as well \$\endgroup\$
    – user41805
    Commented Nov 14, 2019 at 16:57
  • \$\begingroup\$ ah, makes sense \$\endgroup\$ Commented Nov 14, 2019 at 17:05
1
\$\begingroup\$

APL (Dyalog), 3 bytes

Full program body:

2|⎕

Try it online!

Alternatively:

2⊤⎕

Try it online!

| is modulus, is base-convert, is numeric input prompt. Handles any numeric array.

I've found 40 functions which can also do the job in 3 bytes. List and try them all online!

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

Haxe, 22 bytes

function(x)return x%2;

Test it online!

Haxe is a high-level, strictly typed language designed to be compiled across many different platforms. While it doesn't have any form of lambda expressions, it does have one unique property that allows for interesting golfing: everything is an expression. This allows you to do interesting things that aren't possible in most similar languages, such as b>0&&return b. In this particular case, it allows us to remove the brackets that would normally be required in a function definition.

\$\endgroup\$
1
  • \$\begingroup\$ High level language, low level answer (lol) \$\endgroup\$ Commented Mar 23, 2017 at 13:37
1
\$\begingroup\$

Qwerty-RPN, 4 bytes

@2%#

Explanation:

@    Input number
  %  ...modulo...
 2   2
   # print
\$\endgroup\$
1
\$\begingroup\$

Beeswax, 6 bytes

_2~,%{

Explanation:

_        Create a bee flying horizontally   [0,0,0]
 2       Set top to 2                       [0,0,2]
  ~      Swap top and 2nd values            [0,2,0]
   ,     Take value from STDIN as int       [0,2,7]
    %    Modulo: top % 2nd                  [0,0,1]
     {   Print top                          [0,0,1]

Try it online!

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

Ook!, 79 64 bytes

Update: 15 bytes shorter by removing the whitespaces, thanks to Okx.

This is a joke esoteric language, meant to be trivially isomorphic to brainfuck by substituting each command with an Orangutan phrase. This is my first time using it.

Ook.Ook.Ook!Ook?Ook.Ook!Ook.Ook?Ook.Ook!Ook?Ook!Ook?Ook.Ook!Ook.

Try it here! Give input as unary. Output is 1 for odd numbers, and nothing for even ones.

Explanation:

The above script is a direct translation of the 8 bytes brainfuck answer by @Dennis:

+[,>,]<.

Ook! has only 3 distinct syntax elements: Ook., Ook? and Ook!. These are combined into groups of two, and the various pair combinations are mapped to the brainfuck commands.

Substitution table:

>   Ook.Ook?
<   Ook?Ook.
+   Ook.Ook.
-   Ook!Ook!
.   Ook!Ook.
,   Ook.Ook!
[   Ook!Ook?
]   Ook?Ook!
\$\endgroup\$
4
  • \$\begingroup\$ You can golf it by removing the newlines. \$\endgroup\$
    – Okx
    Commented Mar 23, 2017 at 14:27
  • \$\begingroup\$ @Okx On a second look, the online interpreter from my answer works with no whitespace delimiter. Cool! That means I can remove the spaces too. Thanks for pointing that out. I've read the wiki and the Ook! creator's page and only the newlines were said to be ignored, nothing about the spaces. \$\endgroup\$
    – seshoumara
    Commented Mar 23, 2017 at 15:13
  • \$\begingroup\$ Is there really any point to golf it? It is equivalent to BF, just with the byte count multiplied by 8, so golfing it is essentially the same as golfing BF. There's a reason it's not on TIO. \$\endgroup\$ Commented Aug 14, 2020 at 4:45
  • \$\begingroup\$ Looking now at it, no, you're right. But back then if I wouldn't have done it, I wouldn't have known that it works also if you remove the newlines and especially the spaces. I don't think I made another answer in Ook since then. \$\endgroup\$
    – seshoumara
    Commented Aug 14, 2020 at 20:26
1
\$\begingroup\$

Gibberish, 8 bytes

eli2gmeo

eli      - read line, convert to integer
   2gm   - push 2, push modulo of previous value by 2
      eo - output stack

Outout 0 for even and 1 for odd

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

J, 8 chars

<&1@:|~&2

It's just a composition of

<&1

which flips 0 for 1, and

|~&2

which is mod 2.

The @: just composes the two functions together

\$\endgroup\$
2
  • \$\begingroup\$ You don't need <&1@. It's up to us which Boolean corresponds to which parity. Also, 2&| saves a byte. Try it online! \$\endgroup\$
    – Dennis
    Commented Mar 25, 2017 at 12:40
  • 1
    \$\begingroup\$ Welcome to the site! \$\endgroup\$ Commented Mar 31, 2017 at 6:40
1
\$\begingroup\$

Elisp, 12 10 bytes

(%(read)2)

(read) evaluates to the input, and the (% ...) expression is then evaluated. Outputs 1 for odd, 0 for even.

Test cases:

(Input):(Output)
1:1
2:0
16384:0
99999999:1

Edit: Saves 2 bytes thanks to @Dylan, for asking if it was possible to leave out the spaces in a Elisp expression. Turns out the answer is yes!

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

Python REPL, 3 bytes

_&1

Explanation: Taking bitwise and with 1 gives True when even else False

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Just so you know, the downvote was cast automatically by the Community user when you edited your answer. I consider this a bug. \$\endgroup\$
    – Dennis
    Commented Mar 26, 2017 at 15:08
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Commented Mar 26, 2017 at 16:08
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Pavel
    Commented Mar 26, 2017 at 19:40
  • \$\begingroup\$ @ГригорийПерельман thank you \$\endgroup\$ Commented Mar 28, 2017 at 7:33
  • \$\begingroup\$ @Dennis thanks for edit 👍 \$\endgroup\$ Commented Mar 28, 2017 at 7:34
1
\$\begingroup\$

J, 2 bytes

2|         NB. remainder of arg / 2

    So 0 = true (even), 1 = false (odd)
    2| 7   => 1
    2| 10  => 0 
\$\endgroup\$
1
  • \$\begingroup\$ This doesn't look right. I get a syntax error. I think you need another byte: 2|] or 2&| \$\endgroup\$
    – Adám
    Commented May 8, 2017 at 8:55
1
\$\begingroup\$

Scala, 9 bytes

(_:Int)%2

This outputs 1 for odd, 0 for even

\$\endgroup\$
1
3 4
5
6 7
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.