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 2
3
4 5
9
3
\$\begingroup\$

Funciton, 68 bytes

Byte count assumes UTF-16 encoding with BOM.

╓─╖
║p║
╙┬╜┌┐
 ├─┤├
╔╧╗└┘
║1║
╚═╝

Try it online!

This defines a function p which takes a single integer and returns 0 for even and 1 for odd numbers.

Explanation

╓─╖
║p║
╙┬╜

This is the function declaration header. The line leaving the box will emit the input of the function when called.

╔╧╗
║1║
╚═╝

This is a literal. The line leaving the box will emit a 1.

 ├─

This T-junction computes the bitwise NAND of its inputs, and emits it to the right.

   ┌┐
   ┤├
   └┘

Finally, we compute the bitwise NOT, by splitting the value on first T-junction and computing the bitwise NAND with itself on the second T-junction.

The loose end on the right is used as the function's output value. Hence, the overall function computes:

p(x) = NOT(NAND(x, 1)) = AND(x, 1)
\$\endgroup\$
3
\$\begingroup\$

Lua, 20 bytes

print(io.read()%2<1)

This returns true if STDIN mod 2 is 0 and returns false if it isn't. You can also remove the <0 to get the opposite results.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can change ==0 to <1. \$\endgroup\$
    – Pavel
    Mar 26, 2017 at 19:41
3
\$\begingroup\$

OIL, 39 bytes

5
0
9
0
10
0
1
16
9
9
0
10
0
1
17
2
4
4

Explanation:

5 0 reads the input into line 0. 9 0 decrements line 0 (using the fact that the input must be positive (i.e. >0)).

10 0 1 compares line 0 to line 1 (which contains a 0). If they're identical, that means the number must have been odd, jump to cell 16.

9 0 decrements line 0 again. 10 0 1 does the same comparison again, except this time equality means the number was even, jump to cell 17. Otherwise go on with the decrementation process (jump to line 2).

Line 16 and 17 both contain a 4 (print), meaning if we jumped to line 16, 4 4 will print what's in line 4 (10). If we jumped to line 17 instead, 4 (0) will print 0, the value in line 0.

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

TI-Basic-83, 4 bytes

fPart(.5Ans

Gets the partial fraction part of 1/2 multipled by Ans, returns 0 if even, anything else if odd.

\$\endgroup\$
2
  • \$\begingroup\$ It's 11 bytes m8! \$\endgroup\$
    – Daniel W.
    Jul 10, 2017 at 7:50
  • 1
    \$\begingroup\$ @DanFromGermany Ti-Basic is a tokenized language. \$\endgroup\$ Jul 11, 2017 at 3:05
3
\$\begingroup\$

Python, 12 bytes

lambda x:x%2

use with

g = lambda x:x%2
g(a)

where a is the input number. Returns 1 for Odd, and 0 for Even.

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

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!

\$\endgroup\$
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, 2019 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, 2019 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\$
5
  • 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, 2019 at 4:37
  • 1
    \$\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, 2019 at 6:27
  • 1
    \$\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, 2019 at 22:56
  • \$\begingroup\$ No need to use std::io; when you can just put std:: in from of the sole use of io. Incorporating that, and Jo & Esolanging's suggestions gets it down to 113 bytes: fn main(){let mut d="".into();std::io::stdin().read_line(&mut d);print!("{}",d.trim().parse::<i32>().unwrap()%2)}. \$\endgroup\$ Apr 19, 2023 at 15:05
  • \$\begingroup\$ On modern Rust (1.62+, when stdin() spawned the lines() method), you can avoid any let/mut at all by just iterating the lines (it does require unpacking the Result for each line, but since .lines() strips the newline for you, you get to skip the .trim()). Reduces it to just 95 bytes/chars: fn main(){for d in std::io::stdin().lines(){print!("{}",d.unwrap().parse::<i32>().unwrap()%2)}} \$\endgroup\$ Apr 19, 2023 at 15:09
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, 2019 at 6:49
  • \$\begingroup\$ @JoKing neither does the final result? \$\endgroup\$
    – ASCII-only
    Mar 27, 2019 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\$

HP 48 User REPL, 15 bytes

« 1 + 2 MOD
»

French quote marks mark the var as a program

'1 +' - adds one to the number on the stack (input)

'2 Mod'- returns 0 when odd, 1 when even

1 is a truth in RPL and 0 is false, so we have to shift it up once to make it valid.

On the calculator this is 26 bytes despite the source being 15 including nonessential formatting.

\$\endgroup\$
1
  • \$\begingroup\$ Chose a weird language for this one! \$\endgroup\$ Jan 4, 2022 at 1:32
3
\$\begingroup\$

dc, 4 bytes

?2%p

Try it online!

Uses 1 for odd and 0 for even.

Explanation

This is just straightforward modulo.

?    push input onto stack
2    push a 2 onto stack
%    take modulo of input and 2
p    print
\$\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, 2017 at 11:00
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, 2017 at 15:39
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, 2017 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, 2017 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, 2017 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\$

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\$
1
  • 1
    \$\begingroup\$ Is *2 necessary? \$\endgroup\$
    – Leo
    Mar 21, 2017 at 21:28
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, 2017 at 9:49
2
\$\begingroup\$

J-uby, 6 bytes

:even?

In J-uby, Ruby's symbols are callable. Fixnum#even? in Ruby (predictably) returns whether a number is even or not. It can be called like so:

f = :even?
f.(2) #=> true
f.(3) #=> false
\$\endgroup\$
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\$
1 2
3
4 5
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.