67
\$\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

212 Answers 212

1
\$\begingroup\$

MarioLANG, 37 bytes

;>-)+([!)
="=====#:
)![(-)-<
:#====="

Try it online!

Outputs 1 for odd and 0 for even.

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

Kotlin, 15 bytes

{n:Int->n%2<1}
\$\endgroup\$
1
\$\begingroup\$

W, 2 bytes

2m

Basically just modulo by 2...

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

PARI/GP, 6 bytes

n->n%2

Mod 2.

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

CJam, 4 bytes

q~2%

Try it online!

Simple mod by 2. Outputs 1 for odd, 0 for even.

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

Java, 91 bytes

enum d{;public static void main(String[]a){System.out.println(Long.parseLong(a[0])%2==0);}}

Takes number as first command line argument and outputs to STDOUT.

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

bc, 9 bytes

Output is 1 for odd, and 0 for even.

read()%2

Try it online!

A trailing newline is necessary to run successful, and it is included in the bytes count. The read() function works only for numerical input.

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

Applescript function, 26

on f(i)
return i mod 2
end

Test calls

log f(1)
log f(2)
log f(3)
\$\endgroup\$
0
\$\begingroup\$

Go, 26 bytes

func(i int)int{return^i&1}

Returns 1 for even and 0 for odd.

Try it online!

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

Scala, 15 14 5 3 bytes

_%2

Returns 0 if it's an even number and 1 if it's odd

This is equivalent to (i:Int)=>i%2.
However, this needs to be assigned to a variable of type Int=>Int, otherwise the compiler will complain.
The whole code would look like this:

val x: Int => Int = _%2
\$\endgroup\$
  • \$\begingroup\$ Just a tip but you can reduce this by one byte by doing <1 instead of ==0. \$\endgroup\$ – Stefan Aleksić Mar 25 '17 at 14:46
  • \$\begingroup\$ I don't think that's cheating. See here. Notice that Java 8 lambda solutions often leave off the type. \$\endgroup\$ – Brian McCutchon Mar 26 '17 at 23:44
  • \$\begingroup\$ Is the <1 even needed? would it not return 0 if even and 1 if odd? \$\endgroup\$ – fəˈnɛtɪk Mar 27 '17 at 14:49
  • \$\begingroup\$ Depends if we need a boolean, but I guess returning 0 and 1 works too. Thanks! \$\endgroup\$ – 2xsaiko Mar 27 '17 at 19:37
0
\$\begingroup\$

Swift, 18 bytes

let f={n in n%2<1}
\$\endgroup\$
  • \$\begingroup\$ Can be shortened to let f={n in n%2} which would return 0 for even and 1 for odd, saving 2 bytes \$\endgroup\$ – Mr. Xcoder Apr 11 '17 at 14:09
0
\$\begingroup\$

Chip, 2 bytes

For the simple case:

Aa

This only handles one-byte numbers, either a single ASCII digit or a 1 byte unsigned integer (because ASCII code points for odd digits are themselves odd). This works like the &1 bitmask used in many other answers. If multiple bytes are provided, this will treat each new byte as a separate input. Outputs 0x0 for even and 0x1 for odd.

By adding e*f, we can get output in ASCII (5 bytes):

Aae*f

Try it online!

23 + 3 = 26 bytes

For the complex case:

 Svvvvvvvv~t
azABCDEFGH

This handles numbers of any length, ASCII or unsigned integer as before (big endian so that least significant bit is still last). Requires either a null terminator, or the -z flag (as shown in the byte count) to detect the end on the input. Like above, outputs 0x0 for even and 0x1 for odd.

Again, we can add e*f to get ASCII output (25 + 3 = 28 bytes):

*fSvvvvvvvv~t
eazABCDEFGH

Try it online!

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

x86 machine code, 2 bytes

00000000  a8 01                                             |..|
00000002

Sets the zero flag if the value in register A is even.

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

R, 10 bytes

!scan()%%2

If you can get away with assuming n is the value, !n%%2 works.

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

Convex, 3 bytes

Ã2%

Try it online!

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

///, 5 bytes

/00//

Try it online!

Takes input in unary. Input goes after the last /. Prints a 0 of it's even, otherwise prints nothing. Incredibly short for a /// program that actually does soething.

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

x86 machine code, 3 bytes

83 E0 01 (and ax, 1 in nasm)

Explanation:

Anding any number with 1 will return 1 if the number is odd, or 0 if it is even.

 1111 (15)
&0001
-----
 0001

 1110 (14)
&0001
-----
 0000

 0001 (1)
&0001
-----
 0001

 0010 (2)
&0001
-----
 0000

So move a number into AX, use the three bytes, and AX will hold 0 or 1, if the number is even or odd.

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

Python 2, 16 bytes

print(input()%2)

Try it online!

\$\endgroup\$
  • 3
    \$\begingroup\$ Oh I thought you were using Python Two-Thirds \$\endgroup\$ – Matthew Roh Apr 1 '17 at 0:15
  • \$\begingroup\$ This code will spit me an error message. \$\endgroup\$ – Dat Apr 16 '17 at 23:46
  • 1
    \$\begingroup\$ this code is python 2 only, in python 3 it would be: print(int(input())%2) \$\endgroup\$ – Felipe Nardi Batista May 4 '17 at 11:09
  • \$\begingroup\$ Save a byte with print input()%2 \$\endgroup\$ – Josh May 19 '17 at 21:37
0
\$\begingroup\$

Python 3, 21 bytes

print(int(input())%2)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Hello, and welcome to PPCG! This is 17 bytes. However, you need some way of outputting it (i.e. print). \$\endgroup\$ – NoOneIsHere Apr 16 '17 at 23:21
  • \$\begingroup\$ @NoOneIsHere, may I know how did you calculate the size? \$\endgroup\$ – Dat Apr 16 '17 at 23:22
  • \$\begingroup\$ You can calculate the size for example with this online tool. In addition, if there aren't any special Unicode characters in the code, the size in bytes is usually the number of characters. \$\endgroup\$ – Steadybox Apr 16 '17 at 23:41
  • \$\begingroup\$ You can use Python 2 for a few less bytes: print input()%2 is 15 bytes. \$\endgroup\$ – NoOneIsHere Apr 17 '17 at 0:10
0
\$\begingroup\$

J-uby, 5 Bytes

~:%&2

Takes the reversed-arguments version of % and partially applies 2 to it, creating a function which takes x and returns x%2. 0 for even, 1 for odd.

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

Casio-Basic, 9 bytes

mod(n,2)

8 bytes for the function, 1 to add n as an argument.

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

JavaScript, 6 bytes

A function of input n that returns 0 if even and 1 if odd.

n=>n%2
\$\endgroup\$
0
\$\begingroup\$

Triangular, 6 bytes

$.2%m<

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

  $
 . 2
% m <

$ reads an integer to the stack. 2 pushes 2 to the stack. m divides the top two stack values and pushes the remainder. % prints as an integer.

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

Common Lisp, 4 bytes

oddp

Builtin function, like Haskell odd.

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

Check, 4 bytes (non-competing)

>2%p

Explanation: >2 pushes 2 onto the stack, % preforms modulus with the implicit input, and then p prints the result.

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

WolframAlpha, 6 bytes (non-competing)

x mod2

Try it online!

This will output 0 if the value is divisible by 2 and a non-zero value ("truthy") otherwise.

However, if that is not good enough, there's an alternative 11-byte solution using the floor function:

⌊x⌋mod2

Try it online!

Note: Byte count in UTF-8 counted using this resource.


Obviously, Wolfram is not a programming language. However, at the time of writing, the question was ambiguous enough to not explicitly disallow this answer. In spite that, I have marked this as non-competing. Cheers!

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

expr, 6 bytes

$1 % 2

Note expr(1) is a POSIX standard utility and is not a shell built in. It first arrived in UNIX V7.

Normal mod 2. Alternatively could have used a bitwise &

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

ES2018, 8 Bytes

x=o=>o%2

Or, in ES5+typed arrays+intl:

ES5, 25 Bytes

function x(o){return o%2}
\$\endgroup\$
0
\$\begingroup\$

Implicit, 2 bytes

_2

Prints 0 (falsy) for even, 1 (truthy) for odd. Try it online!

     « implicit integer input  »;
_2   « mod top of stack by 2   »;
     « implicit output         »;
\$\endgroup\$
0
\$\begingroup\$

√ å ı ¥ ® Ï Ø ¿ , 4 bytes

Ik@o

Try it online!

Ignore the header/footer on TIO; that's the interpreter for √ å ı ¥ ® Ï Ø ¿

Not as trivial as the other answers that use builtins or %. Outputs 0 for odd and 1 for even.

I    - Take input
 k   - Remove all odd numbers from the stack
  @  - Push the length of the stack
   o - Output

If the input is odd, it is removed from the stack and the length pushed is 0.

If it's even however the length will be 1 (the input)

\$\endgroup\$

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.