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

208 Answers 208

0
\$\begingroup\$

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.

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

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.

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

Perl 5, 6 bytes

Add +1 for -p

#!/usr/bin/perl -p
$_%=2

Try it online!

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

Tcl, 19 bytes

puts [expr $argv%2]

Try it online!

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

Charm, 11 bytes

[ 2 / pop ]

Try it online!

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

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;}
\$\endgroup\$
  • \$\begingroup\$ You could and should provide a link so it can be tested. \$\endgroup\$ – Muhammad Salman Jun 1 '18 at 13:17
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! (1) IF this is GCC you don't need #include. Just use it. \$\endgroup\$ – user202729 Jun 1 '18 at 3:02
  • \$\begingroup\$ (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) \$\endgroup\$ – user202729 Jun 1 '18 at 3:04
  • \$\begingroup\$ (4) YOu can remove two pairs of {}s. \$\endgroup\$ – user202729 Jun 1 '18 at 3:04
  • \$\begingroup\$ 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. \$\endgroup\$ – Marhtini Jun 1 '18 at 3:18
  • \$\begingroup\$ Save 70 bytes Approximately \$\endgroup\$ – Muhammad Salman Jun 1 '18 at 13:03
0
\$\begingroup\$

HadesLang, 20 bytes

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

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

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

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.

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

JavaScript (Node.js), 6 bytes

Prints 0 for even, 1 for odd

a=>a&1

Try it online!

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

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)

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

Python REPL/Shell, 9 bytes

input()&1

returns 0 for even and 1 for odd

\$\endgroup\$
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – Wheat Wizard Jun 1 '18 at 17:43
  • 4
    \$\begingroup\$ We require submissions to be functions (whether named or unnamed), or complete programs, which means you would need a print statement. \$\endgroup\$ – mbomb007 Jun 6 '18 at 22:04
  • 1
    \$\begingroup\$ Note that this answer becomes valid if you change the language to Python REPL. \$\endgroup\$ – Dennis Jun 7 '18 at 4:39
0
\$\begingroup\$

Ahead, 5 bytes

I2%O@

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

Try it online!

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

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
\$\endgroup\$
0
\$\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\$
0
\$\begingroup\$

Tamsin, 19 bytes

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

Try it online!

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

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

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!

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

BotEngine, 3x9=27 (28 bytes)

v  02468
>IRSSSSST
   >>>>>F

Outputs TRUE for odd and FALSE for even.

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

Microscript, 4 bytes

2si%

Microscript II, 4 bytes

2sN%

Prints 1 for odd and 0 for even.

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

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.

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

Underload, 10 bytes

(0)(1)()^S

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

Try it Online!

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

AsciiDots, 16 bytes

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

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

Try it online!

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

05AB1E, 1 byte

É

Try it online!

Explanation

    # implicit input
 É  # push 1 if odd, otherwise push 0
\$\endgroup\$
0
\$\begingroup\$

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}
\$\endgroup\$
0
\$\begingroup\$

Ruby, 6 bytes

n.odd?

Try it online!

I don't know if this is cheating. There's a method definition in the header. Is there a way to skip doing this and pass in a number differently, perhaps?

odd? is a default operation in Ruby.

\$\endgroup\$
  • \$\begingroup\$ Unless there is a way to define anonymous functions in Ruby, I believe this is a snippet, not a complete solution, unfortunately \$\endgroup\$ – caird coinheringaahing Oct 5 at 17:49
0
\$\begingroup\$

MarioLANG, 37 bytes

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

Try it online!

Outputs 1 for odd and 0 for even.

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

Javascript <= ES5, 28 bytes

function i(n){return n%2==1}

If returning 1 or 0 is allowed, than (27 bytes):

function i(n){return n%2&1}
\$\endgroup\$
  • \$\begingroup\$ The second one is invalid JS, but the first is ok. \$\endgroup\$ – Rɪᴋᴇʀ Apr 17 '17 at 21:40
  • \$\begingroup\$ @Riker fixed... \$\endgroup\$ – user68281 Apr 17 '17 at 21:43
  • \$\begingroup\$ 1 or 0 is okay, yes. Also, you might be able to make this an anonymous function or lambda to save some bytes. \$\endgroup\$ – Rɪᴋᴇʀ Apr 17 '17 at 21:52
  • \$\begingroup\$ You don't need the &1 at all, since -1 and 1 are both "truthy" and returning -1, 1, and 0 is allowed since it passes the "truthiness" test, i.e., they're valid values to place in an if() statement and be evaluated as you would expect. \$\endgroup\$ – Patrick Roberts May 17 '17 at 4:43
-1
\$\begingroup\$

Scala 8 bytes

a=>a%2<1

Similar to the Java 8 solution and probably should also include type to compile like this:

 val m:Int=>Boolean=a=>a%2<1 
\$\endgroup\$
  • \$\begingroup\$ Welcome to the site. If you include an explanation of your code (even if short) It will be long enough to fix the title formatting. \$\endgroup\$ – Wheat Wizard Jul 30 at 13:06
  • \$\begingroup\$ Thank you.. I will do that \$\endgroup\$ – user88272 Jul 30 at 14:38

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.