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

222 Answers 222

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

Microscript, 4 bytes

2si%

Microscript II, 4 bytes

2sN%

Prints 1 for odd and 0 for even.

| improve this answer | |
\$\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.

| improve this answer | |
\$\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!

| improve this answer | |
\$\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!

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

vJASS, 259 bytes

//! zinc
library a{function onInit(){trigger t=CreateTrigger();TriggerRegisterPlayerChatEvent(t,Player(0),"",false);TriggerAddAction(t,function(){real r=S2R(GetEventPlayerChatString());string s="0";if(ModuloReal(r,2)==0){s="1";}BJDebugMsg(s);});}}
//! endzinc

Prints 1 for even inputs and 0 for odd inputs.

Explanation

//! zinc
library a{
   function onInit() {
      trigger t = CreateTrigger();

      // Create a CHAT EVENT.
      TriggerRegisterPlayerChatEvent(t,Player(0),"",false);
      TriggerAddAction(t, function(){
         // Convert STRING to Decimal value.
         real r = S2R(GetEventPlayerChatString());
         string s = "0";

         if( ModuloReal(r,2) == 0 ){
            s = "1";
         }

         // Print the result.
         BJDebugMsg(s);
      });
   }
}
//! endzinc

Using Zinc to able to minimize the code.


If you want to get the user's input, you need to add TriggerRegisterPlayerChatEvent.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

asm2bf, 7 bytes

modr1,2

Yes, it compiles. Takes input in r1, writes output to r1. 1 for odd, 0 for even.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

SystemVerilog, 29 bytes

task t(n);$write(n%2);endtask

Prints 1 for odd numbers and 0 for even numbers.

Testbench:

module m;
  initial begin
    t(1);
    t(2);
    t(16384);
    t(99999999);
  end

  task t(n);$write(n%2);endtask
endmodule

Output (VCS on EDA Playground):

 1         0         0         1
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

FEU, 21 bytes

u/x
m/^(xx)+x$/1/x+/0

Try it online!

0 for even, 1 for odd

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 3, 15 bytes

lambda n:n%2==0

Try it online!

Prints True/False when even/odd respectively.

| improve this answer | |
New contributor
Eesa is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ ==0 can be <1 \$\endgroup\$ – Jo King Aug 11 at 7:26
  • \$\begingroup\$ There are two earlier answers that use exactly the same approach but without the (in)equality (printing 1/0 instead of True/False). Does your answer really contribute anything new? \$\endgroup\$ – Dingus Aug 11 at 9:08
-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}
| improve this answer | |
\$\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 
| improve this answer | |
\$\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\$ – Ad Hoc Garf Hunter Jul 30 '19 at 13:06
  • \$\begingroup\$ Thank you.. I will do that \$\endgroup\$ – user88272 Jul 30 '19 at 14:38
1
4 5 6 7
8

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.