74
\$\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\$
15
  • 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
  • 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
  • 3
    \$\begingroup\$ @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) \$\endgroup\$ Mar 22 '17 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 '17 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 '17 at 18:42

243 Answers 243

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

Turing Machine Code, 99 bytes

0 * * r 0
0 _ _ l 1
1 0 0 * A
1 2 2 * A
1 4 4 * A
1 6 6 * A
1 8 8 * A
A * * * halt-e
1 * * * halt-o

Outputs via the halt state, terminating in state halt-e for even or halt-o for odd.

Try it online.

\$\endgroup\$
1
  • \$\begingroup\$ wonder if outputting via the item under the cursor would be valid \$\endgroup\$
    – ASCII-only
    Apr 12 '19 at 7:15
3
\$\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.

\$\endgroup\$
1
  • \$\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\$ Dec 15 '19 at 1:52
3
\$\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!

\$\endgroup\$
3
  • 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\$ Dec 18 '19 at 22:56
3
\$\begingroup\$

Symbolic Python, 6 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 is of course 1 for all inputs.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ _/_ since it's guaranteed to be positive \$\endgroup\$
    – ASCII-only
    Mar 13 '19 at 6:49
  • \$\begingroup\$ @JoKing neither does the final result? \$\endgroup\$
    – ASCII-only
    Mar 27 '19 at 3:58
3
\$\begingroup\$

Arn, 2 bytes

%2

Try it!

Returns 0 for even, 1 for odd. If you want the opposite,

!%2

would work.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Vyxal, 1 byte

Try it Online!

0 for even, 1 for odd.

Alternatively,

Try it Online!

1 for even, 0 for odd.

\$\endgroup\$
1
  • \$\begingroup\$ okay this is unbelievable but again this is a great answer \$\endgroup\$ Jul 14 '21 at 1:45
3
\$\begingroup\$

KonamiCode, 111 109 bytes

>>>>(^^)v(>)>(^)v(>)L(>)>(^)v((>))>(^^)S(^)A(^^)v(^)A(^>)L(^^)v(>)B(^^^)L(^^^)L(^>)>(>)S((^))>(^)B(>)>(^^)<<<

Explanation

KonamiCode lacks a modulo function, so I'm detecting if a number is odd or evenusing the following algorithm:

While a counter is less than the number to check:
    If x is 0:
        Set x to 1
    Else:
        Set x to 0
Output the number

This has the effect of having x be 0 if the input is even, and 1 if it is odd.

Annotated code: (I'm using x to refer to the x value in the above example)

>>> [Raw input, to get the number to check]
[The next few instructions set up the values in memory]
>(^^) [Sets up "x"]
v(>)
>(^) [Sets up the counter]
v(>)
L(>)
  [We are now inside a loop.]
  >(^)
  v((>)) [Increase the counter]
  >(^^) [Go to x's position in memory (address 2)]
  S(^) [Set the comparison buffer to 1]
  A(^^) [If the comparion buffer equals the current memory value, go to L(^^).
  This will happen if x is 1.]
  [This point is only reached if x is not 1]
  v(^) [Sets x to 1]
  A(^>) [If x is 1 jump to L(^>)

  L(^^) [If x was 1 we jumped to here]
  v(>) [Sets x to 0]
  B(^^^) [If x is not 1 jump to L(^^^)


  L(^^^)
  L(^>)
  [Finally, we reset everything and loop again]
  >(>)
  S((^))
  >(^)
B(>)
[Print the result and finish.]
>(^^)
<<<
\$\endgroup\$
2
\$\begingroup\$

jq, 5 characters

.%2<1

Sample run:

bash-4.3$ jq '.%2<1' <<< 16384
true

On-line test:

\$\endgroup\$
1
  • \$\begingroup\$ Aww, Too bad that TIO doesn't have jq. \$\endgroup\$ Mar 21 '17 at 11:00
2
\$\begingroup\$

Ruby, 10 bytes

->x{x&1<1}

True for even, false for odd.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Since both 0 and 1 are truthy, returning 0 or 1 wouldn't be allowed for ruby, right? \$\endgroup\$ Mar 22 '17 at 21:50
  • \$\begingroup\$ Also, are methods allowed for golf submission, or should they all look like functions : would odd? or even? be a correct submission? \$\endgroup\$ Mar 22 '17 at 21:53
  • 1
    \$\begingroup\$ @EricDuminil Correct; in ruby 0 and 1 are both truthy. \$\endgroup\$ Mar 23 '17 at 20:11
2
\$\begingroup\$

Haskell, 8 bytes

(`mod`2)

1 for odd and 0 for even Test cases:

>(`mod`2)1
1
>(`mod`2)2
0
>(`mod`2)999999
1

Alternative with True/False output, 13 bytes

(==0).(`mod`2)

Test cases with repl usage:

>((<1).(`mod`2))1
False
>((<1).(`mod`2))2
True
>((<1).(`mod`2))16438
True
>((<1).(`mod`2))999999
False
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Um odd is a Prelude Haskell function. \$\endgroup\$ Mar 21 '17 at 15:39
2
\$\begingroup\$

Julia 0.5, 5 bytes

isodd

Try it online!

\$\endgroup\$
2
\$\begingroup\$

GNU sed, 7 bytes

This is also a regex only solution. Input in unary is allowed for sed, based on this meta consensus. No truthy / falsy values actually exist in sed, as there are no data types.

Input as unary: 7 bytes. Output is 0 for odd numbers, and nothing for even ones.

s:00::g     # input consists of only zeros (4 -> 0000). Two zeros are deleted as
            #many times as possible. Remaining pattern space is printed implicitly.

Try it online!

Input as decimal: 12 bytes. Output is 1 for odd numbers, and something other than 1 for even.

/[13579]$/c1     # if last char is 1, 3, 5, 7 or 9, then change pattern space to 1.
                 # Otherwise, do nothing. Implicit printing done at the end.

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ You could use d instead of c1 for the decimal version. sed doesn't really have anything truthy/falsy, and the empty string matches /^$/ so you could use that as your definition of truthy. \$\endgroup\$
    – Riley
    Mar 21 '17 at 14:51
  • \$\begingroup\$ Or you could remove the second line all together and switch c0 to c1. Then odd outputs 1 and even outputs something other than 1. \$\endgroup\$
    – Riley
    Mar 21 '17 at 14:54
  • \$\begingroup\$ @Riley I like your second idea. Initially, I used the least known sed command, =, to print 1 (as in number of input lines), but one needs the -n flag also to suppress implicit printing. \$\endgroup\$
    – seshoumara
    Mar 21 '17 at 15:02
2
\$\begingroup\$

SQLite, 10 bytes

SELECT x%2

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Groovy, 7 bytes

{!it%2}

Answer too short for posting.

\$\endgroup\$
2
\$\begingroup\$

Forth, 11 bytes

: f 2 mod ;

Try it online

Output is 0 if even, 1 if odd.

\$\endgroup\$
2
\$\begingroup\$

Jelly, 2 bytes

Here's an alternate approach to this Jelly answer by ais523

BṪ

B   convert the input to binary
 Ṫ  and return its last character: 0 for even, 1 for odd.

Try it online!

Also at 2 bytes, the classical Modulo 2:

%2

Try it online!

which also returns 0/1 for even/odd resp.

\$\endgroup\$
2
\$\begingroup\$

TacO, 29 bytes

   2i i
  i -+*2
@+%#?v
    1

Outputs 1\n if even, or just \n if odd.

This takes all multiples of 2 from 2 to 2n, removes all the ones in which n - i ~= 0 and sets the rest to 1, then sums that list.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Perl 6, 4 bytes

*%%2

Try it

This is a WhateverCode lambda closure that takes one positional argument.

Expanded:

*   # the parameter   (turns the expression into a WhateverCode)
%%  # is divisible by
2   # two
\$\endgroup\$
2
\$\begingroup\$

Wise, 4 bytes

:><^

Try it Online! (Takes input through command line arguments for now)

Prints 1 for odd, 0 for even.

        Implicit input
:       Duplicate
 ><     Bitshift right, then left, which changes the least significant bit to 0
   ^    Xors with original
        Implicit output

A number is odd if the least significant bit is 1. By xoring the input and the input with the least significant bit as 0, we get 1 on odd numbers (0 != 1), and 0 on even (0 == 0)

\$\endgroup\$
2
\$\begingroup\$

Campfire, 8 bytes

Prints 1 for odd input or 0 for even input, then exits with an error.

&2&2%.%.

Campfire is an esoteric programming language I've created a couple of months ago. While it has a builtin for computing remainders, its unique flow of instructions makes even this simple challenge not so trivial (even if in this case the source turns out to be quite symmetric and nice).

In Campfire, after executing each instruction, the instruction pointer jumps to just after the next occurrence of the instruction just executed (wrapping between the end and the start of the code). Moreover, if the value on the top of the main stack is not 0, the instruction pointer is turned around before jumping (when backwards, it jumps to just before the previous occurrence of the executed instruction).

Here's an explanation of the execution of this program. * marks the instruction executed at each step, and <,>, or ? marks the spot where the instruction pointer will jump to, along with its direction.

&2&2%.%.
* <          & takes a number from input and pushes it to the stack.
             Since we're dealing only with strictly positive numbers,
             we will always switch direction.
 * >         Push 2 to the stack (then switch direction)
    * ?      Compute remainder. If the result is 1 we will switch direction,
             if it's 0 we won't.
 #First alternative:
&2&2%.%.
     * <     Output the result, the stack is now empty, and an empty stack
             has impicit 0s on it, so we won't switch direction.
      *      Try to compute remainder, but the stack is composed only by
             implicit 0s, so this will exit the program with an error.
 #Second alternative:
&2&2%.%.
     > *     We execute the other output instruction, result is the same.
      *      Again, we end by computing 0%0.
\$\endgroup\$
2
\$\begingroup\$

Python 2 REPL, 9 bytes

input()%2

Sample run:

>>>input()%2
42
0

Outputs 0 for even and 1 for odd

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

ZX Spectrum BASIC, 35 31 characters

Thanks to @Leo for removing 4 characters!

I don't know how to obtain the true (tokenized) program size, so the indicated score is in characters

1 INPUT a
2 PRINT a/2-INT(a/2)

Output is 0.5 (which is truthy) for odd input, and 0 (which is falsy) for even input.

This was tested on the Windows SpecBAS interpreter.

enter image description here

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is *2 necessary? \$\endgroup\$
    – Leo
    Mar 21 '17 at 21:28
  • 1
    \$\begingroup\$ @Leo It isn't! Thanks! \$\endgroup\$
    – Luis Mendo
    Mar 21 '17 at 22:34
2
\$\begingroup\$

TI-Basic, 4 bytes

fPart(Ans/2

Other solutions:

remainder(Ans,2         5 bytes - returns 0 even 1 odd

Returns 0 for even numbers and 1/2 for odd numbers. These values evaluate to false and true respectively in TI-Basic.

\$\endgroup\$
2
\$\begingroup\$

C, 11 bytes

f(n){n&=1;}

Because, why not. Returns false (0) for even, true (1) for odd.

Works with gcc on linux/x86.

\$\endgroup\$
1
  • \$\begingroup\$ Huh. Looks okay. \$\endgroup\$ Mar 23 '17 at 9:49
2
\$\begingroup\$

Vim Macro 54 Bytes

^vehxiF^[ve"nyo1234567890^MFTFTFTFTFT^[k@njvyo^[pi^[k$vggx

This Vim Macro works on any file that contains just an integer. During the cleanup process, it removes all the code above itself. This can probably be better implemented where it cleans up only the code it wrote but that would require more bytes.

The ^[ is escape (return to normal mode) and the ^M is the enter key.

What this basically does is it removes everything but the last digit of the number, prepends F to it, saves that into register n so now register n holds F<your number>. Then, it creates two new lines. One containing 1234567890 and the other line containing FTFTFTFTFT. Once it creates the second line, the cursor moves up, executes the n macro, thus finding backwards the first occurrence of <your number>, going down one line to the second line, yanking the corresponding true or false character from it, creating a new line, pasting that character, and then deleting everything it just did.

Vim Macros present a really interesting challenge and require you to think in a different way than what you're used to. It was super cool to work on this.

\$\endgroup\$
2
\$\begingroup\$

Scala, 14 Bytes

(x:Int)=>x%2<1
\$\endgroup\$
0
2
\$\begingroup\$

PHP, 14 bytes

<?=$argv[1]&1;

When I test for odd or even, I only look at the first bit and not % the whole integer.

\$\endgroup\$
2
\$\begingroup\$

Klein, 18 17 16 + 3 bytes, (non-competing)

Uses the 001 topology. Embedded in a Klein Bottle

1(/+@
-+)-($?/:1

Explanation

Here is a gif of it running on 6:

enter image description here

The general way this works is it continually decrements the input down to zero each time multiplying a saved value by -1. That way the saved value will be negative if odd and positive if even.

Setup

Right as the program begins running it does its set up

1(

This puts a 1 on the scope. This is the number we will multiply by -1 to keep track of the parity.

We then use a mirror to deflect the ip of the top of the screen. Since we are on a Klein Bottle and not a Torus this deflection will not only bring us to the bottom but also flip our horizontal coordinate. The ip will move upwards through mostly blank space until it hits another mirror. This mirror puts it in the main loop.

Main Loop

In the main loop we make a duplicate of the input and decrement it by one, multiply the scoped value by -1 using )-( and then we switch the copied version of the counter with the original, we copied it earlier because ? our conditional jump consumes a value. Since ? skips the mirror we will run until our counter is zero.

However since we are checking the copy of the counter, we will actually exit when we hit -1. This is important because it saves us from having to make a value later.

Cleanup

Once we hit zero we are deflected again but the mirror. This sends us over the top of the screen. Since we are on a Klein Bottle this twists us back around and causes the ip to collide with the ) used in part of the code. This is convenient because it recalls the scoped value to the stack. We then get deflected by one of the mirrors from before. Lastly we add the two values, the counter and the saved value. The counter will always be -1 so we are essentially just subtracting 1 from the saved value. The saved value will be either 1 or -1 so our result is either -2 or 0. Then we end and output using @.

\$\endgroup\$
0
2
\$\begingroup\$

newline 19 bytes

g\n0\n/\n[\nd\n]

and the number 2

\$\endgroup\$
1 2
3
4 5
9

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.