# Is this even or odd?

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


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>

• This isn't the first time I've confused mathematical with computational parity... this is a code site after all! – Neil Mar 21 '17 at 10:38
• Since this is pretty much one of these(1,2,3) questions, it should probably have a snippet to see all the answers. – fəˈnɛtɪk Mar 21 '17 at 13:57
• @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. – mbomb007 Mar 21 '17 at 16:37
• @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) – Calvin's Hobbies Mar 22 '17 at 2:46
• @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! – Matthew Roh Mar 23 '17 at 15:09

# Brain-Flak, 10 bytes

({{}[{}]})


Try it online!

Takes input via unary. Odd corresponds to 1, even to 0. Basically alternates between adding and subtracting the unary values to a total until it runs out of numbers and pushes the total. If the number is odd, then there is an extra 1 and it returns 1.

# 17, 40 bytes

1 for odd, 0 for even. It takes input until a newline is entered and then prints mod 2 of last byte. It is not competing because 17 was made after the question was released, through not specifically made for this challenge.

0{I : a == 0 @}1{0 @ 2 % }777{0 0 @}

• Welcome to the site! We allow languages to be created after the challenge so no need to bother with "not competing". – Ad Hoc Garf Hunter Feb 4 '18 at 20:48

# Momema, 13 bytes

z*-8 01z0-8*0


Try it online! Outputs 0 for odd, 1 for even.

## Explanation

Momema's control flow is in the form of named jumps, which also function as labels. Ungolfed, this program is:

z   *-8
0   1
z   0
-8  *0


Each jump instruction takes an argument n and evaluates it. Its semantics are "jump past n jump instructions from here, ignoring any that don't share my label and cyclically wrapping around the program as necessary if one is not found."

That last part—the cyclic wrapping—is important here. An even parameter will continue searching for jump instructions and finish on the first jump instruction, and an odd parameter will finish on the second jump instruction. In the first case, the assignment statement will fill cell 0 (initially with value 0) with value 1. After that, it encounters a jump instruction, but since the argument is 0, it has no effect. Finally, in both cases, -8 outputs the value of cell 0 in decimal, and its value will be set to 0 if and only if the input integer was even.

If outputting nothing for odd/something for even is allowed, the following program works for 10 bytes:

z*-8-8 1z0


# Piet, 10 codels

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.

# Whitespace, 30 bytes

[S S S T    S N
_Push_2][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_number][T    T   T   _Retrieve][S N
T   _Swap_top_two][T    S T T   _Modulo][T  N
S T _Output]


Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Outputs 0 for even, 1 for odd.

Try it online.

Explanation (with 5 as input):

Command    Explanation             Stack      Heap     STDIN    STDOUT

SSSTSN     Push 2                  [2]        {}
SNS        Duplicate top (2)       [2,2]      {}
SNS        Duplicate top (2)       [2,2,2]    {}
TNTT       Read STDIN as number    [2,2]      {2:5}    5
TTT        Retrieve                [2,5]      {2:5}
SNT        Swap top two            [5,2]      {2:5}
TSTT       Modulo                  [1]        {2:5}
TNST       Output top as number    []         {2:5}             1


# 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?

# SmileBASIC, 13 bytes

INPUT N?N<<31


SB uses 32 bit integers, so shifting left by 31 places will preserve only the lowest bit. Even numbers become 0 (falsey), odds become -2147483548 (truthy).

Works on both positive and negative numbers.

# ActionScript 2.0, 36 bytes

function a(b){trace(!Boolean(b%2));}
function a(b){                       - define a function taking one argument:
trace(                 - output
!                - the opposite of
Boolean(        - the next bit converted to boolean:
b%2     - the function's argument mod 2
));} - finish defining the function


a(2); traces 'true', a(3); traces 'false'

Note: it could probably be made smaller if it didn't matter what the output format was, but I think this is pretty small if it has to be a boolean, and you could obviously cut it down by one if you didn't mind true meaning odd and false meaning even.

# Perl 5, 6 bytes

Add +1 for -p

#!/usr/bin/perl -p
$_%=2  Try it online! # Tcl, 19 bytes puts [expr$argv%2]


Try it online!

# Charm, 11 bytes

[ 2 / pop ]


Try it online!

# C (gcc), 17

This does not require any headers. & is bitwise AND; it runs way faster than regular operators. Example: f(7)=> 7 is 111 => 111 AND 1 is 1. If a number's last digit in base 2 is 0, it is even. Else, it is odd. And &1 runs way faster than %2.

f(i){return i&1;}

• You could and should provide a link so it can be tested. – Muhammad Salman Jun 1 '18 at 13:17

# C (gcc), 109 99 bytes

#include <stdio.h>
void main(){int n;scanf("%d",&n);if(n&1)printf("%d:1",n);else printf("%d:0",n);}


Try it online!

C (gcc), 82 bytes : If we are only returning Integers 0 or 1 and not explicitly printing.

#include <stdio.h>
int main(){int n;scanf("%d",&n);if(n&1)return 0;else return 1;}


Try it online!

EDIT: Thanks @user202729 for your suggestions! They've been implemented and it cut a good 10 bytes off the code! Wasn't able to implement the printf() and scanf() functions without the #include statement so going to look some more into that. 0 now means True (or Odd in this case) and 1 now means False (or Even in this case).

A brief explanation:

Originally, I was going to use the printf() prototype instead of including stdio.h. However, the need for scanf() to take input ruined the C minimalism a bit. :)

First we initialize an integer "n", our number we're checking parity for. Then we scanf() for the user to enter the value of n. Since we are able to determine if a number is odd or even by determining if it's first bit (farthest to the right, lowest) is set or unset (1 or 0). In this case, a bit set to 1 means the number is odd, whereas a bit set to 0 means the number is even. The code checks for Odd (True), and else Even.

• Welcome to PPCG! (1) IF this is GCC you don't need #include. Just use it. – user202729 Jun 1 '18 at 3:02
• (2) use conditional operator should be able to save a lot of bytes. (3) By "truthy/falsy value" it don't need to be exactly the string True and False, just 0 and 1 are enough. (see Interpretation of Truthy/Falsy) – user202729 Jun 1 '18 at 3:04
• (4) YOu can remove two pairs of {}s. – user202729 Jun 1 '18 at 3:04
• Thanks for the guidance and the welcome @user202729! First time with code golfing, trying to be more efficient with my code so I figured Golf Challenges were the way to go. – Marhtini Jun 1 '18 at 3:18
• Save 70 bytes Approximately – Muhammad Salman Jun 1 '18 at 13:03

raw:[in:[]] % 2 is 0


in:[] Reads from console
raw:[] Converts a string to any required datatype

# Eukleides, 20 bytes

print number()mod 2


It's trivial, but at least Eukleides has an entry now. number() is the function to take a number as input, and you're supposed to pass it a string to use as a prompt. I thought for sure I'd had to actually pass an empty string before, but I'm not getting an error, so I'll take it. Since it's a simple mod 2, 1 means odd and 0 means even.

# JavaScript (Node.js), 6 bytes

Prints 0 for even, 1 for odd

a=>a&1


Try it online!

# Unnamed, 15 Bytes

This takes an input and prints 1 if its odd, 0 if even.

; # _%.@0.2 # .


## How?

" # " is the command separator.

;   take input as integer and put it into the cuurent cell (0)
_   assign                                    to the current cell (0)
%.                                   modulo
@0.2       the value in the 0th cell        2
.   print the value in the current cell


Try it (paste the code into the first textarea and write your input to the second one. press run and the output will appear in the third area)

## Python REPL/Shell, 9 bytes

input()&1


returns 0 for even and 1 for odd

• This answer doesn't actually seem to output anything. I'd suggest either making it a lambda or using print to make it actually produce output. – Ad Hoc Garf Hunter Jun 1 '18 at 17:43
• We require submissions to be functions (whether named or unnamed), or complete programs, which means you would need a print statement. – mbomb007 Jun 6 '18 at 22:04
• Note that this answer becomes valid if you change the language to Python REPL. – Dennis Jun 7 '18 at 4:39

I2%O@


1 == true == odd. 0 == false == even.

Try it online!

# Pepe, 14 bytes

rEeEreEEEEreEE


Try it online! (Fails in large cases like 99999999999999999)

0 for even, 1 for odd

Explanation:

rEeE           # input as int
reEEEE     # ...mod 2
reEE # output int


# Tamsin, 19 bytes

main={"0"&"0"}&eof.


Try it online!

Takes input in unary. Recognizes an even number of 0 characters.

# Gol><>, 5 bytes

I2%zh


take input, push 2, modulo a, b, then if the number was even, output 1, otherwise output 0

Try it online!

# BotEngine, 3x9=27 (28 bytes)

v  02468
>>>>>F


Outputs TRUE for odd and FALSE for even.

# Microscript, 4 bytes

2si%


# Microscript II, 4 bytes

2sN%


Prints 1 for odd and 0 for even.

# Pyramid Scheme, 185 149 bytes

     ^
/=\
^---^
^-  /#\
^-  ^---
/#\ /+\
---^---^
/"\ ^-
^---/"\
-^ ^---
//\-
^---^
-^ /2\
/#\---
---^
/ \
/arg\
^-----
-^
/1\
---


Try it online!

Uses a different method from Khuldraeseth's answer, and outputs 1 for odd numbers, 0 for even. This takes input as a command line argument. This basically equates to:

a = int(input())/2
print(a == int(str(a) + str(0)))


This works because a string like "0.5"+"0" is converted to the float 0.5, whereas "1"+"0" will be 10. This means numbers already with a decimal point will ignore the added 0.

(0)(1)()^S


Input is in hard-coded in Unary, using ~ in the 3rd bracket. 0 for odd, 1 for even.

Try it Online!

# AsciiDots, 16 bytes

.-#?{&}\$#
.-#1/


Outputs 0 if even, and 1 if odd. Basically just a Boolean AND with 1.

Try it online!

# 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}


# Python 3, 12 bytes

lambda n:n&1


Outputs 1 for odd, 0 for even.

# 05AB1E, 1 byte

É


Try it online!

## Explanation

   # implicit input
É  # push 1 if odd, otherwise push 0
`