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

250 Answers 250

1
5 6 7 8
9
0
\$\begingroup\$

Kotlin, 19 bytes

fun a(n:Int)=n%2==0

This was surprisingly simple. And the code is pretty self explanatory.

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

Duocentehexaquinquagesimal, 6 bytes

5Q¬$††

Try it online!

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

Python 3, 16 bytes

x=lambda n:n%2<1

Try it online!

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

INTERCAL, 39 bytes

Domain is ZERO or OH to FOUR TWO NINE FOUR NINE SIX SEVEN TWO NINE FIVE. _ (zero) for even and I (one) for odd. Also works in CLC-INTERCAL.

DOWRITEIN:1DO:1<-':1~#1'PLEASEREADOUT:1

Try it online!

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

INTERCAL (C-INTERCAL), 229 bytes

This version accepts any integers, in decimal (e.g. -156); requires to be terminated with EOF.

Outputs _ for even and I for odd.

DO,1<-#1DOCOMEFROM#3DOWRITEIN,1(1)DO.1<-,1SUB#1DO.2<-.4DO(1000)NEXTDO.4<-.3PLEASE.3<-!3~#15'$!3~#240'DO.3<-!3~#15'$!3~#240'DO.2<-!3~#15'$!3~#240'PLEASE.1<-.5DO(1010)NEXT(3)DO.5<-.2PLEASECOMEFROM.1~#256DO.2<-.2~#128PLEASEREADOUT.2

Try it online!

How it works

  • First part is taken from 229 bytes of cat program but without READing out character.
  • In ASCII 0 is 48, 1 is 49, ... 9 is 57.
  • But C-INTERCAL reverses bit order, so 0 is 0x0c, 1 is 0x8c, ... 9 is 0x9c.
  • If bit at 0x80 is 1, then it's odd digit.
\$\endgroup\$
0
\$\begingroup\$

LOLCODE, 151 bytes

HAI 1.2
I HAS A N
GIMMEH N
N IS NOW A NUMBAR
I HAS A V ITZ QUOSHUNT OF N AN 2
VISIBLE MAEK BOTH SAEM DIFF OF V AN MAEK V A NUMBR AN 0.5 A NUMBR
KTHXBYE

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ bruh u can just use the MOD OF operator: Try it online! \$\endgroup\$
    – Steffan
    May 4 at 2:44
0
\$\begingroup\$

Python REPL, 14 bytes

int(input())%2

Where 0 (falsy) is even, and 1 (truthy) is odd.

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

Headascii, 20 13 bytes

{UN()}:R--O<E

Try it here! Code will have to be copied and executed like this:

erun("{UN()}:R--O<E","input here")

Outputs two differing error messages. For odd inputs:

error 0:12 E [ 1, 0, 0, 1 ] (1)
'Error: E index out of range'

For even inputs:

error 0:12 E [ 1, 0, 0, 1 ] (2)
'Error: E index out of range'

Explanation:

{UN()}:R--O<E  Full program (Block 0)

{    }         Loop, which
 U             Discard(s) input byte(s)
  N() :        Until there is no input
  N(           (and stores 1 in the comparison register)
       R       Recall the last byte
        --O    Subtract 2 and save
           <   If this number is less than the comparison register (1)
                 Return the number in the comparison register (1)
               Else
                 Return 0
            E  Go to the code block corresponding to this number.
               If it is block 0, the program loops to the beginning
               with the saved byte as "input"
               If it is block 1, the program will exit with an error,
               as there is no block 1 in this program. The error message
               will include register state information, including the
               currently recall-able byte. In this state of the program,
               odd inputs will have reached 1, and even inputs will have
               reached 2.

I still think this is further golfable, but I'm proud of this clever little -7

Old solution (20 bytes):

{UN)}:R--O(<)[E:+()?

Try it here! Code will have to be copied and executed like this:

erun("{UN)}:R--O(<)[E:+()?","input here")

Prints a Headascii debug message if odd, and nothing if even.

Explanation:

{UN)}:R--O(<)[E:+()?  Full program

{   }                 Loop which
 U                    Discard(s) input byte(s)
  N) :                Until there is no more input
      R               Recall the last byte (as a number)
       --O            Subtract 2 and save
          (<)         If the number is greater than or equal to 0
             [E         Return to start of program, with saved number as input
               :      Else
                +()     If the number is -1
                   ?      Print a debug message

Repeatedly subtracts 2 from the last digit until it is -1 or -2. There might be a way to shave off a byte or two by switching the conditions / thens / elses around a bit. Just want to submit for now

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

K (ngn/k), 5 bytes

{2!x}

Try it online!

0 for true, 1 for false.

\$\endgroup\$
1
  • \$\begingroup\$ You can just do 2! instead of an explicit block \$\endgroup\$
    – Jo King
    May 6 at 14:40
-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\$
4
  • \$\begingroup\$ The second one is invalid JS, but the first is ok. \$\endgroup\$
    – Riker
    Apr 17, 2017 at 21:40
  • \$\begingroup\$ @Riker fixed... \$\endgroup\$
    – user68281
    Apr 17, 2017 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\$
    – Riker
    Apr 17, 2017 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\$ May 17, 2017 at 4:43
1
5 6 7 8
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.