68
\$\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\$
  • 2
    \$\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 '17 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\$ – fəˈnɛtɪk Mar 21 '17 at 13:57
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ – mbomb007 Mar 21 '17 at 16:37
  • 2
    \$\begingroup\$ @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) \$\endgroup\$ – Calvin's Hobbies Mar 22 '17 at 2:46
  • 3
    \$\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\$ – Matthew Roh Mar 23 '17 at 15:09

222 Answers 222

1 2 3
4
5
8
2
\$\begingroup\$

Poetic, 190 bytes

although i agree i,a person,i was dismissive about a hell,i am not anarchic
i repeat:i know theres never a hell i am doomed to
actually,it seems a bit of a fraud,a lie,if He gives a man he|l

Try it online!

Input is in decimal. Output is an Unexpected EOF error for even inputs, and a Mismatched IF/EIF error for odd inputs. It takes forever to actually execute, though.

(Doesn't work for 0, but the question only specified positive inputs.)

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Shakespeare Programming Language, 137 bytes

Try it online!

#.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen tothy.You is the remainder of the quotient betweenyou a big cat.Open heart

Fairly simple, just outputs the input mod 2. Maybe improvable.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Oof, why didn't I test and why is this language so weird. Rolled back. Thank you! I just tested to make sure it didn't error lol. \$\endgroup\$ – Hello Goodbye Dec 15 '19 at 1:52
2
\$\begingroup\$

Rust, 148 bytes

use std::io;fn main(){let mut d=String::new();io::stdin().read_line(&mut 
 Rd);d=d.trim().to_string();let b=d.parse::<i32>().unwrap()%2;print!("{}",b)}

I'm really bad with rust, so this probably isn't very optimal, but I didn't see any other rust answers.

Try it online!

| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ Hey, welcome to the Code Golf Stack Exchange! I hope you enjoy your stay here. Nice answer by the way! \$\endgroup\$ – Lyxal Dec 16 '19 at 4:37
  • \$\begingroup\$ Is there any point to the b variable, or the added d assignment? Why not just define a function that takes a number rather than all the reading from stdin stuff? \$\endgroup\$ – Jo King Dec 16 '19 at 6:27
  • \$\begingroup\$ If you want to keep this as a full program, you can use "".into() instead of String::new() to save a few bytes. \$\endgroup\$ – Esolanging Fruit Dec 18 '19 at 22:56
2
\$\begingroup\$

Pyramid Scheme, 221 199 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 (- n 1))))
  (set! n (- n 2)))
(display n)

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

MAWP, 9 bytes

@!!2P2WA:

Try it!

Just a homemade modulo function. Outputs 1 if odd and 0 if even

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ That's unfair! :( The continous addition of built-ins here and there makes it much more golfier than 1+ (which cannot be updated, otherwise it's no longer 1+!) \$\endgroup\$ – HighlyRadioactive Aug 11 at 9:05
  • \$\begingroup\$ @HighlyRadioactive I mean, the only builtin thats really beneficial is the input method - the rest is the modulo function !!xPxWA (where x is the number by which to modulo) that i invented :D \$\endgroup\$ – Dion Aug 11 at 9:15
  • \$\begingroup\$ Alright, fair enough. I try to [compete with MAWP] with 1+, because both of them are easy-to-use "Turing-tarpit-ish" languages. \$\endgroup\$ – HighlyRadioactive Aug 11 at 9:21
  • \$\begingroup\$ @HighlyRadioactive challenge accepted! :D \$\endgroup\$ – Dion Aug 11 at 9:22
  • \$\begingroup\$ :D You should keep a "MAWP answer list" somewhere... \$\endgroup\$ – HighlyRadioactive Aug 11 at 9:26
1
\$\begingroup\$

Brachylog, 3 bytes

%₂0

Try it online!

Explanation

Well…

%₂0     Input mod 2 = 0
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Cardinal, 7 bytes

%++~:M.

Outputs truthy if odd falsy if even

Try it online!

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C, 15 bytes

#define f(n)n&1

Returns 0 if even, 1 if odd.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 7 Bytes

#'evenp

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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Julia 0.5, 5 bytes

isodd

Try it online!

| improve this answer | |
\$\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!

| improve this answer | |
\$\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)
| improve this answer | |
\$\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%
| improve this answer | |
\$\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)
| improve this answer | |
\$\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.

| improve this answer | |
\$\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

| improve this answer | |
\$\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 ò
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Cool approach, I like it! Alternate (but very similar) approach: Àé1Ó11 \$\endgroup\$ – James Mar 21 '17 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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Alternatively, 2|]. \$\endgroup\$ – Conor O'Brien Mar 21 '17 at 18:37
  • \$\begingroup\$ um... what does the ']' do? \$\endgroup\$ – Bijan Mar 21 '17 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\$ – Conor O'Brien Mar 21 '17 at 19:24
  • \$\begingroup\$ An APL expression for all the 3-byte J expressions that are valid answers \$\endgroup\$ – Adám Mar 23 '17 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.

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

LibreLogo, 19 bytes

Code:

print int input "%2

Result:

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

| improve this answer | |
\$\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.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jellyfish, 6 bytes

p|i
 2

Try it online!

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

| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ That's okay. Every answer else is trivial too. At least it's not a builtin. \$\endgroup\$ – Matthew Roh Mar 23 '17 at 9:32
  • \$\begingroup\$ Why do you have to convert to float? \$\endgroup\$ – Hello Goodbye Nov 14 '19 at 16:27
  • \$\begingroup\$ @HelloGoodbye Because it is by default a string, although yes, I should work just as well \$\endgroup\$ – user41805 Nov 14 '19 at 16:57
  • \$\begingroup\$ ah, makes sense \$\endgroup\$ – Hello Goodbye Nov 14 '19 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!

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ High level language, low level answer (lol) \$\endgroup\$ – Matthew Roh Mar 23 '17 at 13:37
1
\$\begingroup\$

Qwerty-RPN, 4 bytes

@2%#

Explanation:

@    Input number
  %  ...modulo...
 2   2
   # print
| improve this answer | |
\$\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!

| improve this answer | |
\$\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!
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can golf it by removing the newlines. \$\endgroup\$ – Okx Mar 23 '17 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 Mar 23 '17 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\$ – HighlyRadioactive yesterday
  • \$\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 20 hours ago
1 2 3
4
5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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