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){return e.lang>s.lang?1:e.lang<s.lang?-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>

share|improve this question
1  
This isn't the first time I've confused mathematical with computational parity... this is a code site after all! – Neil yesterday
    
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 yesterday
    
@mbomb007 Why the change from Catalogue to Leaderboard? – Mike Bufardeci yesterday
1  
@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 yesterday
    
is 0 an even number? – tuskiomi yesterday

95 Answers 95

ArnoldC, 299 283 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
GET TO THE CHOPPER i
HERE IS MY INVITATION i
I LET HIM GO 2
ENOUGH TALK
TALK TO THE HAND i
YOU HAVE BEEN TERMINATED

This outputs 1 (which is truthy) for odd input and 0 (which is falsy) for even input.

Try it online!

share|improve this answer
8  
My first ArnoldC answer! – Luis Mendo yesterday
3  
BULLSHIT YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER – carusocomputing yesterday
2  
GET YOUR ASS TO MARS ...I have no words. – SIGSEGV yesterday
2  
I joined this community to upvote this. Well done, sir – Erik 14 hours ago
    
@Erik Haha. Thanks, and welcome to PPCG! – Luis Mendo 14 hours ago

Retina, 8 bytes

[02468]$

A Retina answer for decimal input. This is also a plain regex solution that works in almost any regex flavour. Matches (and prints 1) for even inputs and doesn't match (and prints 0) for odd inputs.

Try it online!

An alternative, also for 8 bytes, uses a transliteration stage to turn all even digits to x first (because transliteration stages have a built-in for even/odd digits):

T`E`x
x$

Of course, the shortest input format (even shorter than unary) would be binary in this case, where a simple regex of 0$ would suffice. But since the challenge is essentially about finding the least-signficant binary digit, binary input seems to circumvent the actual challenge.

share|improve this answer
    
+1 for "TeX". Makes me want to see a LaTeX answer... – Brevan Ellefsen 12 hours ago

Mathematica, 4 bytes

OddQ

Gives True for odd inputs and False for even inputs, who knew?

There's also EvenQ, but who would want to type all of that?

share|improve this answer
6  
Oh, no. builtins again. – SIGSEGV yesterday
3  
@SIGSEGV That's Mathematica for ya. ;) – Kevin Cruijssen yesterday
1  
2∣#& works also – Kelly Lowder 11 hours ago
    
@KellyLowder true but that's 6 bytes. – Martin Ender 11 hours ago

brainfuck, 8 bytes

+[,>,]<.

Input is in unary. Output is the 1 (truthy) for odd numbers and NUL (falsy) for even numbers.

Try it online!

share|improve this answer

Python, 11 10 bytes

-1 byte thanks to Griffin

1 .__and__

Try it online!
Using bitwise and, returns 0 for even and 1 for odd

share|improve this answer
2  
1 .__and__ is one char shorter – Griffin yesterday

brainfuck, 14 bytes

Input and output is taken as character codes as per this meta.
Byte value 1 correspond to odd numbers and 0 to even.

+>>,[-[->]<]<.

Try it online!

share|improve this answer

Taxi, 1,482 1,290 1,063 bytes

I've never written a program in Taxi before and I'm a novice in programming for general, so there are probably better ways to go about this. I've checked for errors and managed to golf it a bit by trying different routes that have the same result. I welcome any and all revision.

Returns 0 for even and 1 for odd.

Go to Post Office:w 1 l, 1 r, 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l, 1 r.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l, 1 l, 1 l, 2 l.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:e 1 l, 2 r, 3 r, 2 r, 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l, 1 l, 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Equal's Corner.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to Knots Landing.Go to Knots Landing:n 4 r, 1 r, 2 r, 1 l.[a]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 l, 1 r.Go to Taxi Garage:n 1 r, 1 l, 1 r.[b]0 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 r.Pickup a passenger going to Knots Landing.Go to Knots Landing:w 1 r, 2 r, 1 r, 2 l, 5 r.Switch to plan "a".

You're right, that's awful to read without line breaks. Here's a formatted version:

Go to Post Office:w 1 l, 1 r, 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l, 1 r.
Pickup a passenger going to Divide and Conquer.
2 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l, 1 l, 1 l, 2 l.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer:e 1 l, 2 r, 3 r, 2 r, 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:e 1 l, 1 l, 2 l.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Equal's Corner.
Go to Trunkers:s 1 l.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner:w 1 l.
Switch to plan "b" if no one is waiting.
Pickup a passenger going to Knots Landing.
Go to Knots Landing:n 4 r, 1 r, 2 r, 1 l.
[a]
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:w 1 l.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l, 1 r.
Go to Taxi Garage:n 1 r, 1 l, 1 r.
[b]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 r.
Pickup a passenger going to Knots Landing.
Go to Knots Landing:w 1 r, 2 r, 1 r, 2 l, 5 r.
Switch to plan "a".

Here's my best attempt to explain the logic:

Go to Post Office to pick up the stdin value in a string format.
Go to The Babelfishery to convert the string to a number.
Go to Starchild Numerology to pickup the numerical input 2.
Go to Divide and Conquer to divide the two passengers (stdin & 2).
Go to Cyclone to create a copy of the result.
Go to Trunkers to truncate the original to an integer.
Go to Equal's Corner to see if the two passengers are the same.
Equal's Corner returns the first passenger if they're the same (no .5 removal so the stdin was even) or nothing if they're not.
If nothing was returned, it was odd, so go pick up a 0 from Starchild Numerology.
Go to Knots Landing to convert any 0s to 1s and all other numbers to 0s.
Go to The Babelfishery to convert the passenger (either a 1 or 0 at this point) to a string.
Go to Post Office to print that string.
Go to Taxi Garage to terminate the program.
share|improve this answer
1  
I always learned that goto is evil – aross 16 hours ago
    
Not only does the language require the extensive use of go to, the only branching method is by using plans, which are just a different name for goto. – Engineer Toast 16 hours ago

Fireball, 1 byte

Explanation:

◘    Implicit input mod 2

Fireball is a heavy WIP programming language created by me.

Prints 0 for even values, and 1 for odd.

Try it online!

share|improve this answer

LOLCODE, 67 bytes

HOW DUZ I C YR N
  VISIBLE BOTH SAEM MOD OF N AN 2 AN 0
IF U SAY SO

Function that returns WIN (true) if number is not prime, else (prime) it will return FAIL (false).

Call with C"123".

share|improve this answer

MATL, 5 3 bytes

Because builtins are boring

:He

This outputs a matrix of nonzero values (which is truthy) for even input, and a matrix containing one zero (which is falsy) for odd input.

Try it online! The footer code is an if-else branch to illustrate the truthiness or falsihood of the result. Removing that footer will implicitly display the matrix.

Explanation

Consider input 5 as an example

:     % Implicitly input n. Push row vector [1 2 ... n]
      % STACK: [1 2 3 4 5]
He    % Reshape into a 2-row matrix, padding with zeros if needed
      % STACK: [1 3 5;
                2 4 0]
share|improve this answer
3  
'Builtins are boring' HeAA, HeAA, HeAA.(Sorry that was a bad pun) – SIGSEGV yesterday
    
@SIGSEGV HeHeHe – Luis Mendo yesterday
1  
Clever approach! :) – Stewie Griffin yesterday

Japt, 1 byte

v

Returns 1 for even numbers, 0 for odd.

Try it online!

Explanation

One of Japt's defining features is that unlike most golfing languages, functions do not have fixed arity; that is, any function can accept any number of arguments. This means that you can sometimes leave out arguments and Japt will guess what you want. v on numbers is a function that accepts one argument and returns 1 if the number is divisible by the argument, else 0. It just so happens that the default argument is 2, thereby solving this challenge in a single byte.


2-byte solution (1 byte +1 byte for the -h flag):

¢

¢ converts the input into a base-2 string. The -h flag returns the last char from the string.

Try it online!

share|improve this answer

brainfuck, 12 bytes

,++[>++]>++.

This requires an interpreter with a circular tape and cells that wrap around. The one on TIO has 65,536 8-bit cells and satisfies the requirements.

I/O is in bytes. Odd inputs map to 0x00 (falsy), even inputs to a non-zero byte (truthy).

Try it online!

How it works

We start by reading a byte of input with , and adding 2 to its value with ++. We'll see later why incrementing is necessary.

Next, we enter a loop that advances to the cell at the right, add 2 to it, and repeats the process unless this set the value of the cell to 0.

Initially, all cells except for the input cell hold 0. If the input is odd, adding 2 to it will never zero it out. However, after looping around the tape 127 times, the next iteration of the loop will set the cell to the right of the input cell to 128 × 2 = 0 (mod 256), causing the loop to end. >++ repeats the loop body one more time, so next cell is also zeroed out and then printed with ..

On the other hand, if the input is n and n is even, the code before the loop sets the input cell to n + 2. After looping around the tape (256 - (n - 2)) / 2 = (254 - n) / 2 times, the input cell will reach 0, and the cell to its right will hold the value (254 - n) / 2 × 2 = 254 - n. After adding 2 with >++, . will print 256 - n = -n (mod 256), which is non-zero since n is non-zero.

Finally, note that the second case would print 258 - n = 2 - n (mod n) if we didn't increment the input before the loop, since one more loop around the tape would be required to zero out the input cell. The program would thus fail for input 2.

share|improve this answer
    
How does this work? It seems to loop around increasing every cell by two. When does it leave the loop? When the cell overflows? – Luke yesterday
    
Yes, and depending on the parity of the input, this will happen in the input cell itself or one cell to the right. I'll add a detailed explanation when I have time. – Dennis yesterday
    
I've added an explanation. – Dennis yesterday

Java 8, 8 bytes

n->n%2<1

Java 7, 30 bytes

Object c(int n){return n%2<1;}

Outputs true for even numbers and false for odd numbers

Try it here.


If 1/0 would be allowed instead of true/false (it doesn't considering the numbers of votes here):

  • Java 8 (6 bytes): n->n%2
  • Java 7 (25 bytes): int c(int n){return n%2;}
share|improve this answer
7  
Where is all the ridiculously verbose Java-stuff? I feel this is at least 50 bytes too short... – Stewie Griffin yesterday
    
@StewieGriffin Hehe, yeah, Java 8 turns out to be pretty short for some challenges. :) 8 bytes for this challenge, actually competing with the rest (except for the 1 / 2 byte answers from code-golf languages). Yesterday I posted this answer, which is also competing with it's 19 bytes. Who knows, perhaps Java will ever win one (Not!.. ;p). (PS: Makes me wonder: Is there a single challenge on this SE with a Java answer as accepted answer? xD Definitely not for code-golf, but perhaps code-challenge or something similar.) – Kevin Cruijssen yesterday
1  
Once upon a time there was a tag called code-trolling. But this one is a very nice accepted Java-answer, and here is a code-golf answer. And some more. – Stewie Griffin yesterday
    
@StewieGriffin Ah yes, I've seen those answers before. (About a year ago when I was sorting all questions/answers by vote and was looking at all of them one by one.) Too bad code-trolling isn't a tag anymore, looks like a lot of fun to create something as verbose and useless as possible for something that can usually be done with a single builtin. – Kevin Cruijssen yesterday

C++, 25 bytes

template<int v>int o=v&1;

This defines a variable template (a function-like construct) with value equal to the bitwise operation input&1. 0 for even values, 1 for odd values. The value is calculated on compile-time.

Requires C++14.

Try it online!

share|improve this answer
    
Woah, that seems really clever. I've never seen an answer like this before! How do you call this? – DJMcMayhem yesterday
    
@DJMcMayhem It's a simple use of C++14's variable templates. It's not all that clever, though: A simple function aproach (int o(int v){return v&1;}) would take the same amount of bytes, with the difference that the value would be calculated at runtime. – Cássio Renan yesterday

C#, 8 bytes

n=>n%2<1

Compiles to a Func<int, bool>.

Or if an anonymous function is disallowed, this method for 21 bytes:

bool p(int n)=>n%2<1;
share|improve this answer
    
I don't think you need the <1. 1 and 0 are acceptable outputs. – obarakon 2 hours ago

JavaScript, 6 bytes

An anonymous function:

n=>n&1

Alternatively with the same length:

n=>n%2

Both will return 0|1 which should fulfill the requirement for truthy|falsey values.

Try both versions online

share|improve this answer
    
According to the Java answer this doesn't fulfil the requirements. Is JavaScript different in this regard? – TheLethalCoder yesterday
1  
The question clearly states "This is not required, You may use other Truthy/Falsy values", which 0|1 are, right? @TheLethalCoder – insertusernamehere yesterday
    
I'm not sure if they are in JavaScript that's what I was asking, see the meta q/a to see if they are. I'm not familiar enough in JavaScript to know. – TheLethalCoder yesterday
    
JavaScript is much more laxly typed than Java. It's happy to treat pretty much anything as any type. In particular, it's happy to treat floats as booleans (whereas Java will throw a compile-time error if you do this). (By the way, you possibly don't want to know why this returns a float rather than an integer.) – ais523 yesterday
    
@TheLethalCoder Ah, thanks for the meta post. It makes the answer clear: Yes, they are valid. – insertusernamehere yesterday

Sinclair ZX81 BASIC 124 bytes (listing)

 1 INPUT A
 2 IF A<1 THEN STOP
 3 LET A=INT A
 4 LET B=INT (A/2)
 5 LET M=A-B*2
 6 PRINT A;":";
 7 GOSUB (M+1)*10
 8 RUN
10 PRINT "TRUE"
11 RETURN
20 PRINT "FALSE"
21 RETURN

Line 3 can be removed to save at least 10 bytes, although it is there to ensure that only integer numbers are excepted (i.e., anything after the decimal point is ignored by the program listing). It's basically doing the closest you'll get to a modulo on ZX81 (or most other 8-bit) BASIC interpreters, so A % 2 is passed to M - then we call the sub-routine at (M+1)*10 which will either print TRUE and return, or FALSE.

There are probably a few ways to save bytes, but it's functioning. I may refactor later. Entering a number less that 1 will exit the program.

ZX81 in action - true or false

share|improve this answer

Pyth, 3

I was expecting pyth to have a 1 or 2 byte builtin for this. Instead here are the best solutions I could find:

%Q2

or

.&1

or

e.B
share|improve this answer

05AB1E, 1 byte

È

Fairly self-explantory. Returns a % 2 == 0

Try it online!

share|improve this answer
    
É is a better choice, in my personal opinion; kidding. – carusocomputing yesterday

Jelly, 1 byte

Try it online!

Just another builtin.

For people who don't know Jelly: it has quite a bit of ability to infer missing bits of code, thus there isn't much syntactic difference between a snippet, a function, and a full program; the interpreter will automatically add code to input appropriate arguments and output the result. That's pretty handy when dealing with PPCG rules, which allow functions and programs but disallow snippets. In the TIO link, I'm treating this as a function and running it on each integer from 1 to 20 inclusive, but it works as a full program too.

Jelly, 2 bytes

&1

Try it online!

It's pretty short without the builtin, too. (This is bitwise-AND with 1.)

share|improve this answer

Retina, 3 bytes

11

The trailing newline is significant. Takes input in unary. Outputs 1 for odd numbers, nothing for even numbers. Try it online!

share|improve this answer
    
You know, you can just copy the full answer (with the necessary formatting for the trailing linefeed) from TIO. – Martin Ender yesterday
    
@MartinEnder No, I didn't know. – Neil yesterday
    
It's the second-to-last snippet when you generate the permalink. – Martin Ender yesterday
    
Oh, it's a whole snippet? I just see the title line. – Neil yesterday
    
@Neil if you click in the snippet, it will expand it and you'll see the body – Dada yesterday

Labyrinth, 5 bytes

?_2%!

Prints 0 for even and 1 for odd inputs.

Try it online!

?   Read input.
_2  Push 2.
%   Modulo.
!   Print.

Now the instruction pointer hits a dead end and turns around. Upon attempting the % on an empty stack, the program exits due to division by zero.

alternatively, also 5 bytes

?#&!@

Try it online!

?   Read input.
#   Push stack depth (1).
&   Bitwise AND (extract least-significant bit).
!   Print.
@   Terminate.
share|improve this answer
    
Would #?#%! or _?#%! work too? – Mistah Figgins yesterday
    
@MistahFiggins yes. – Martin Ender yesterday

7, 18 characters, 7 bytes

177407770236713353

Try it online!

7 doesn't have anything resembling a normal if statement, and has more than one idiomatic way to represent a boolean. As such, it's hard to know what counts as truthy and falsey, but this program uses 1 for odd and the null string for even (the truthy and falsey values for Perl, in which the 7 interpreter is written). (It's easy enough to change this; the odd output is specified before the first 7, the even output is specified between the first two 7s. It might potentially need an output format change to handle other types of output, though; I used the two shortest distinct outputs here.)

7 uses a compressed octal encoding in which three bytes of source represent eight bytes of program, so 18 characters of source are represented in 7 bytes on disk.

Explanation

177407770236713353
 77  77     7       Separate the initial stack into six pieces (between the 7s)

        023         Output format string for "output integers; input one integer"
       7   6        Escape the format string, so that it's interpreted as is
             13     Suppress implicit looping
               3    Output the format string (produces input)
                5   Run the following code a number of times equal to the input:
   40                 Swap the top two stack elements, escaping the top one
                 3  Output the top stack element

Like many output formats, "output integers" undoes any number of levels of escaping before outputting; thus 40, which combined make a swap-and-escape operation, can be used in place of 405, a swap operation (which is a swap-and-escape followed by an unescape). If you were using an output format that isn't stable with respect to escaping, you'd need the full 405 there. (Incidentally, the reason why we needed to escape the format string originally is that if the first output contains unrepresentable characters, it automatically forces output format 7. Escaping it removes the unrepresentable characters and allows format 0 to be selected.)

Of the six initial stack elements, the topmost is the main program (and is consumed by the 13 that's the first thing to run); the second is the 023 that selects the output format and requests input, and is consumed by that operation; the third is consumed as a side effect of the 3 operation (it's used to discard stack elements in addition to producing output); the fourth, 40, is the body of the loop (and consumed by the 5 that executes the loop); and the fifth and sixth are swapped a number of times equal to the input (thus end up in their original positions if the input is even, or in each others' positions a

You could golf off a character by changing the leading 177 to 17 (and relying on an implicit empty sixth stack element), but that would change the parity of the outputs to a less idiomatic method than odd-is-true, and it doesn't save a whole byte (the source is still seven bytes long). As such, I decided to use the more natural form of output, as it doesn't score any worse.

share|improve this answer

Brain-Flak, 22 20 bytes

Here is annother cool answer in Brain-Flak you should also check out

(({})){({}[()]<>)}<>

Try it online!

Explanation

To start we will make a copy of our input with (({})).

The bottom copy will serve as a truthy value while the top one will be used for the actual processing. This is done because we need the input to be on the top and it is rather cumbersome to put a 1 underneath the input.

Then we begin a loop {({}[()]<>)}. This is a simple modification on the standard countdown loop that switches stacks each time it decrements.

Since there are two stacks an even number will end up on the top of the stack it started on while an odd number will end on the opposite stack. The copied value will remain in place and thus will act as a marker of where we started.

Once we are done with the loop we have a 0 (originally the input) sitting on top of either a truthy (the copy of the input) or falsy (empty stack) value. We also have the opposite value on the other stack.

We need to get rid of the 0 which can be removed either by {} or <>. Both seem to work and give opposite results, however {} causes a falsy value for zero, when it should return truthy. This is because our "truthy" value is a copy of the input and zero is the only input that can be falsy.

This problem is resolved by ending the program with <> instead.

(Of course according to the specification I do not technically have to support zero but give two options I would prefer to support it)

share|improve this answer

Piet, 15 codels / 16 bytes

Source Code

5njaampjhompppam

Online interpreter available here.

This program returns 0 if the input is even and 1 if the input is odd.

The text above represents the image. You can generate the image by pasting it into the text box on the interpreter page. For convenience I have provided the image below where the codel size is 31 pixels. The grid is there for readability and is not a part of the program.

Explanation

This program uses the modulo builtin to determine if the input is even or odd.

Instruction    Δ Hue   Δ Lightness   Stack
------------   -----   -----------   -------
In (Number)    4       2             n
Push [2]       0       1             2, n
Modulo         2       1             n % 2
Out (Number)   5       1             [Empty]
[Exit]         [N/A]   [N/A]         [Empty]

The dark blue codels in the bottom-left are never visited and can be changed to any color other than a color of a neighboring codel. I chose dark blue as I think it looks nice with the rest of the program. The top-left black codel could also be white, but not any other color. I have chosen black as I think it looks nicer.

I have provided the program in both image form and text form as there is no clear consensus on how to score Piet programs. Feel free to weigh in on the meta discussion.

share|improve this answer

TIS-100, 39 bytes

Of course, this is, more precisely, a program for the T21 Basic Execution Node architecture, as emulated by the TIS-100 emulator.

I'll refer you to this answer for a fantastically in-depth explanation of the scoring for TIS-100 programs, as well as their structure.

@0
ADD UP
G:SUB 2
JGZ G
MOV ACC ANY

Explanation:

@0          # Indicates that this is node 0
ADD UP      # Get input and add it to ACC, the only addressable register in a T-21
G:          # Defines a label called "G"
SUB 2       # Subtracts 2 from ACC
JGZ G       # If ACC is greater than 0, jumps to G
MOV ACC ANY # Sends the value of ACC to the first available neighbor; in this case, output.
            # Implicitly jump back to the first line

In pseudocode, it'd look something like:

while (true) {
    acc = getIntInput()
    do {
        acc -= 2
    } while (acc > 0)
    print(acc)
}

The T21 doesn't have boolean types or truthy/falsy values, so the program returns -1 for odd numbers and 0 for even numbers, unless the previous input was odd, in which case it returns -1 for even numbers and 0 for odd numbers - if that fact disturbs you, this is a full-program answer, so you can just restart your T21 between uses.

share|improve this answer
    
I was just thinking of TIS-100, the Zachtronics puzzle game, since I wanted to buy it last week. Is TIS an actual language also, or does it exist only in that video game? – seshoumara yesterday
    
@seshoumara To my knowledge, it only exists within the game. The entire architecture of machines in TIS is kinda typical, and this Assembly-style language hooks into that. – steenbergh yesterday
    
I can confirm, it only exists in the game (and in fact, even in-universe it's a weird and bizarre architecture). I wrote the answer Turtleman linked to as if there were real TIS devices, but I only did it in character for fun. – undergroundmonorail 6 hours ago

Batch, 16 bytes

@cmd/cset/a%1%%2

Outputs 1 for odd, 0 for even. Alternative 16-byte version also works on negative numbers:

@cmd/cset/a"%1&1

17 bytes to output 1 for even, 0 for odd:

@cmd/cset/a"~%1&1
share|improve this answer
    
Your program only echoes the MOD result, which is incorrect. The question said the output format should be"(Input):(Output)" – SteveFest yesterday

Octave, 12 bytes

@(x)mod(x,2)

Takes x modulus 2. Returns 0 for even numbers and 1 for odd numbers. These evaluates to false and true respectively in Octave. This works in MATLAB too.

share|improve this answer

Sesos, 2 bytes

SASM

set numin
get
jmp, sub 2

SBIN

00000000: 1228                                              .(

Output is via exit code, zero for even and non-zero for odd. Odd inputs may take a long time.

Try it online!

How it works

This is a bit cheaty, but it complies with our rules.

The program reads a decimal integer from STDIN and keeps subtracting 2 until it reaches 0. For even inputs, this finishes in linear time and does nothing, successfully.

Programs that do not contain the set mask directive use arbitrary precision integers, so odd inputs will slowly continue to allocate memory. Once the available memory is exhausted, the program will get killed, resulting in a non-zero exit code. Don't expect this to happen anytime soon...

Alternate version, 3 bytes

SASM

set numin
get
jmp, sub 2

SBIN

00000000: 124601                                            .F.

Output is via exit code, zero for even and non-zero for odd. Stray output to STDOUT should be ignored.

Try it online!

How it works

Marginally less cheaty. The program works as before, but also prints the tape cell as a character in each iteration. This will exit with an error once the cell becomes negative.

share|improve this answer

Hexagony, 7 bytes

?{2\%'!

Prints 0 for even numbers (falsy) and 1 for odd numbers (truthy).

Try it online!

Explanation

Here is the folded code:

 ? {
2 \ %
 ' !

I believe this is optimal although not unique. As usual I've run a brute force search (not an exhaustive one, but the characters I've excluded are very unlikely to be useful for this program). It did find a whole bunch of other solutions, which I haven't investigated in detail yet:

^?"2^%!
^?"2}%!
{?"2^%!
{?"2}%!
2^?\%"!
2}?\%"!
\{?2%'!
2^?")%!
2^?"1%!
2^?"2%!
2^?=^%!
2{?"}%!
2{?'=%!
2{?={%!
2}?")%!
2}?"1%!
2}?"2%!
2}?=^%!
|"?^2%!
)>"?}!%
\}2?%"!
2^=?^%!
2{'?^%!
2{=?{%!
2}=?^%!

As for the solution I've picked above:

?   Read input.
{   Move to the left memory edge.
    The IP wraps around to the left corner.
2   Set the memory edge to 2.
\   Deflect the IP southwest.
'   Move to the memory edge that points at the input and at the 2.
    The IP wraps around to the right corner.
%   Take the input modulo 2.
!   Print the result.
    The IP wraps to the top right corner.
{   Move to the input edge, which points at two empty edges.
%   Attempt to take the modulo of those, which terminates the program 
    due to the attempted division by zero.

I did look at the next program the above list, which is quite fun because it loops through the first two lines 6 times, filling an entire hexagonal ring with 2s before wrapping back around to the first and taking the modulo. At that point it actually uses the second 2 for the computation. I'm sure there are some gems in the others as well, but I don't think I'll have the time to go through them in detail.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.