81
\$\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
    Commented 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\$ Commented Mar 21, 2017 at 13:57
  • 3
    \$\begingroup\$ @tuskiomi The challenge only asks about positive integers. (0 is considered even but not positive) \$\endgroup\$ Commented 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\$ Commented 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
    Commented Mar 26, 2017 at 18:42

264 Answers 264

1
2 3 4 5
9
131
\$\begingroup\$

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!

Now this is the plan” (An attempt at an explanation)

The code reads the input into variable i, replaces it with the result of modulo 2, and then prints it.

IT'S SHOWTIME                                    # BeginMain
HEY CHRISTMAS TREE i                             #   Declare i
YOU SET US UP 0                                  #   SetInitialValue 0
GET YOUR ASS TO MARS i                           #   AssignVariableFromMethodCall i
DO IT NOW                                        #   CallMethod
I WANT TO ASK YOU ... ANSWERED IMMEDIATELY       #   ReadInteger
GET TO THE CHOPPER i                             #   AssignVariable i
HERE IS MY INVITATION i                          #     SetValue i (push i on the stack)
I LET HIM GO 2                                   #     ModuloOperator 2
ENOUGH TALK                                      #   EndAssignVariable
TALK TO THE HAND i                               #   Print i
YOU HAVE BEEN TERMINATED                         # EndMain
\$\endgroup\$
12
  • 30
    \$\begingroup\$ My first ArnoldC answer! \$\endgroup\$
    – Luis Mendo
    Commented Mar 21, 2017 at 14:01
  • 20
    \$\begingroup\$ BULLSHIT YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER \$\endgroup\$ Commented Mar 21, 2017 at 14:27
  • 22
    \$\begingroup\$ GET YOUR ASS TO MARS ...I have no words. \$\endgroup\$ Commented Mar 21, 2017 at 16:00
  • 18
    \$\begingroup\$ I joined this community to upvote this. Well done, sir \$\endgroup\$
    – Erik
    Commented Mar 22, 2017 at 15:23
  • 3
    \$\begingroup\$ I joined this community to upvote this post as well. :) \$\endgroup\$ Commented Mar 24, 2017 at 4:52
51
\$\begingroup\$

brainfuck, 8 bytes

+[,>,]<.

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

Try it online!

How it works

We start by incrementing the current cell with + to be able to enter the while loop [,>,].

In each iteration, , reads a byte from STDIN, > advances to the cell to the right, then , reads another byte from STDIN. When input is exhausted, the interpreter (the one on TIO, anyway) will set the cell to NUL instead. Once that happens, the condition of the while loop is no longer fulfilled and we break out of it.

Let n be the input integer. If there is an even amount of input bytes – i.e., if n is even – the first n/2 iterations will read two 1's, and the next iteration will read two NUL's, leaving the tape as follows.

...   1  NUL  NUL
...  49    0    0
                ^

<. retrocedes one cell and prints its content, sending a NUL byte to STDOUT.

However, if there is an odd amount of input bytes, the first (n - 1)/2 iterations will read two 1's, and the next iteration will read one 1 and one NUL, leaving the tape as follows.

...   1    1  NUL
...  49   49    0
                ^

< will now retrocede to a cell holding the byte/character 1, which . prints.

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

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?

\$\endgroup\$
9
  • 24
    \$\begingroup\$ Oh, no. builtins again. \$\endgroup\$ Commented Mar 21, 2017 at 10:43
  • 10
    \$\begingroup\$ @SIGSEGV That's Mathematica for ya. ;) \$\endgroup\$ Commented Mar 21, 2017 at 10:44
  • 11
    \$\begingroup\$ 2∣#& works also \$\endgroup\$ Commented Mar 22, 2017 at 18:47
  • 1
    \$\begingroup\$ @KellyLowder true but that's 6 bytes. \$\endgroup\$ Commented Mar 22, 2017 at 19:00
  • 2
    \$\begingroup\$ @Cyoce most predicates do, like IntegerQ or SortedQ. I suppose it stands for "question" or "query", but I don't know. \$\endgroup\$ Commented Jun 17, 2017 at 7:54
32
\$\begingroup\$

Taxi, 1,482 1,290 1,063 1,029 1,009 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.[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".

Try it online!

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.
[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.
Try and fail to go to Starchild Numerology because the directions are wrong so the program terminates.

Not going back to the Taxi Garage causes output to STDERR but I'm fine with that.

\$\endgroup\$
2
  • 9
    \$\begingroup\$ I always learned that goto is evil \$\endgroup\$
    – aross
    Commented Mar 22, 2017 at 13:37
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 22, 2017 at 13:51
27
\$\begingroup\$

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

\$\endgroup\$
3
  • 3
    \$\begingroup\$ 1 .__and__ is one char shorter \$\endgroup\$
    – Griffin
    Commented Mar 21, 2017 at 12:28
  • \$\begingroup\$ Such an awesome abuse of the language! \$\endgroup\$ Commented Nov 14, 2019 at 14:45
  • \$\begingroup\$ @Dion well, you still need to add print to be a full program, my code is a funcion (like a lambda) so it can be used directly \$\endgroup\$
    – Rod
    Commented Jun 2, 2020 at 16:14
25
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ +1 for "TeX". Makes me want to see a LaTeX answer... \$\endgroup\$ Commented Mar 22, 2017 at 18:19
23
\$\begingroup\$

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 even, else (odd) it will return FAIL (false).

Call with C"123".

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

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 with a zero in its lower right entry (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]
\$\endgroup\$
3
  • 7
    \$\begingroup\$ 'Builtins are boring' HeAA, HeAA, HeAA.(Sorry that was a bad pun) \$\endgroup\$ Commented Mar 21, 2017 at 11:22
  • 3
    \$\begingroup\$ @SIGSEGV HeHeHe \$\endgroup\$
    – Luis Mendo
    Commented Mar 21, 2017 at 11:28
  • 2
    \$\begingroup\$ Clever approach! :) \$\endgroup\$ Commented Mar 21, 2017 at 11:37
19
\$\begingroup\$

Java 8, 8 bytes

n->n%2<1

Try it here.

Java 7, 30 bytes

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

Try it here.

Outputs true for even numbers and false for odd numbers


If 1/0 would be allowed instead of true/false (it isn'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;}
\$\endgroup\$
11
  • 26
    \$\begingroup\$ Where is all the ridiculously verbose Java-stuff? I feel this is at least 50 bytes too short... \$\endgroup\$ Commented Mar 21, 2017 at 12:10
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 21, 2017 at 12:20
  • 2
    \$\begingroup\$ @lukeg Hi, the default is program or function, unless the challenge states otherwise. Which means languages like Java and C# are allowed to post just the function (and required imports) instead of the entire class. If the question-asker would specifically ask for a program, then I indeed have to include the borderline code like the class/interface and main-method. \$\endgroup\$ Commented Mar 24, 2017 at 7:50
  • 1
    \$\begingroup\$ @lukeg If you want to start answering challenges yourself, here are some tips for golfing in Java which might be interesting to read through. Welcome to PPCG! :) \$\endgroup\$ Commented Mar 24, 2017 at 7:50
  • 7
    \$\begingroup\$ @StewieGriffin There you go! int o(int n){return java.util.stream.IntStream.of(n).map(n->n%2).filter(n==0).fi‌​ndAny().isPresent();‌​} \$\endgroup\$ Commented Mar 24, 2017 at 12:31
17
\$\begingroup\$

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.

\$\endgroup\$
15
\$\begingroup\$

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!

\$\endgroup\$
15
\$\begingroup\$

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

\$\endgroup\$
6
  • \$\begingroup\$ According to the Java answer this doesn't fulfil the requirements. Is JavaScript different in this regard? \$\endgroup\$ Commented Mar 21, 2017 at 11:33
  • 5
    \$\begingroup\$ The question clearly states "This is not required, You may use other Truthy/Falsy values", which 0|1 are, right? @TheLethalCoder \$\endgroup\$ Commented Mar 21, 2017 at 11:35
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 21, 2017 at 11:37
  • 5
    \$\begingroup\$ 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.) \$\endgroup\$
    – user62131
    Commented Mar 21, 2017 at 11:38
  • 1
    \$\begingroup\$ Good :) I wasn't familiar enough to know myself so was just wondering. \$\endgroup\$ Commented Mar 21, 2017 at 11:42
14
\$\begingroup\$

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. For example:

v3

This program will output 1 if the input is divisible by 3, and 0 otherwise. It just so happens that the default argument is 2, thereby solving this challenge in a single byte.


Alternative 1 byte solution:

¢

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

Try it online!

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

Sinclair ZX81 BASIC 124 bytes 114 bytes 109 bytes 57 50 42 tokenized BASIC bytes

Another release candidate:

 1 INPUT A
 2 IF A THEN PRINT A;":";NOT INT A-(INT (INT A/VAL "2")*VAL "2")

As per Adám's comments below:

 1 INPUT A
 2 IF NOT A THEN STOP
 3 PRINT A;":";NOT INT A-(INT (INT A/VAL "2")*VAL "2")

It will now PRINT 1 for even and 0 for odd. Zero exits.

Here are older versions of the symbolic listing for reference purposes:

 1 INPUT A
 2 IF NOT A THEN STOP
 3 LET B=INT (INT A/2)
 4 PRINT A;":";NOT INT A-B*2
 5 RUN

Here is the old (v0.01) listing so that you may see the improvements that I've made as not only is this new listing smaller, but it's faster:

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

And here is v0.02 (using Sinclair sub strings):

 1 INPUT A
 2 IF NOT A THEN STOP
 3 LET B=INT (INT A/2)
 4 LET M=1+INT A-B*2
 5 LET C=4*(M=2)
 6 PRINT A;":";"TRUE FALSE"(M+C TO 5+C+(M=2))
 7 RUN

ZX81 in action - true or false from v1/2

\$\endgroup\$
4
  • 1
    \$\begingroup\$ This is not kolmogorov-complexity. You just have to return 0 or 1 for any given input. \$\endgroup\$
    – Adám
    Commented Mar 23, 2017 at 10:04
  • \$\begingroup\$ The question looks like it was edited since I made my initial entry as it <i>read</i> like true/false required to be returned. As such, I can simplify the symbolic listing further. \$\endgroup\$ Commented Mar 23, 2017 at 10:14
  • 1
    \$\begingroup\$ Why do you need to exit on zero? Can't you just PRINT (A-2*INT A/2)/A? \$\endgroup\$
    – Adám
    Commented Mar 24, 2017 at 11:43
  • \$\begingroup\$ In the original question, which has been helpfully edited, it specified that the value 0 should not produce a TRUE or FALSE, hence as 0 wasn't supposed to produce a result then I had it STOPping the program. I probably interpreted the original question as it was posted by @SIGSEGV a little too literally. Yes, one can optimize and refactor, you are correct. \$\endgroup\$ Commented Mar 24, 2017 at 12:02
11
\$\begingroup\$

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.

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

Intel 8080 machine code, 1 byte

1F      RAR     ; rotate accumulator's least significant bit into Carry Flag

Input is in A, result is CF=1 if odd, CF=0 if even.

Here is a test program for the MITS Altair 8800 that will take the input number and display the result (odd or even) on the front panel lights. Just follow these programming instructions on the front panel switches:

Step    Switches 0-7    Control Switch  Instruction Comment
1                       RESET
2       00 111 110      DEPOSIT         MVI  A, 27  Load number to examine into A
3       00 011 011      DEPOSIT NEXT                Set value to test (27 in this case)
4       00 011 111      DEPOSIT NEXT    RAR         Rotate A's LSB into CF
5       11 110 101      DEPOSIT NEXT    PUSH PSW    Push Status Flags to stack
6       11 000 001      DEPOSIT NEXT    POP  B      Pop Status Flags to BC register
7       00 111 110      DEPOSIT NEXT    MVI  A, 1   CF is LSB (0x1) of Status Flags
8       00 000 001      DEPOSIT NEXT
9       10 100 001      DEPOSIT NEXT    ANA  C      Mask CF so is only result displayed
10      11 010 011      DEPOSIT NEXT    OUT  255    display contents of A on data panel
11      11 111 111      DEPOSIT NEXT
12      01 110 110      DEPOSIT NEXT    HLT         Halt CPU
13                      RESET                       Reset program counter to beginning
14                      RUN
15                      STOP
                                                    D0 light will be on if value is odd,
                                                    or off if even

If entered correctly, the program in RAM will look like: 0000 3e 1b 1f f5 c1 3e 01 a1 d3 ff 76

To re-run with a another number:

Step    Switches 0-7    Control Switch      Comment
1                       RESET
2       00 000 001      EXAMINE             Select memory address containing value
3       00 000 010      DEPOSIT             Enter new value in binary (2 in this case)
4                       RESET
5                       RUN
6                       STOP

Try it online! Just follow the easy steps above!

Output

Input = 27, light D0 is ON indicating ODD result:

enter image description here

Input = 2, light D0 is OFF indicating EVEN result:

enter image description here

\$\endgroup\$
4
  • 2
    \$\begingroup\$ The same code works on the Z80 too :) \$\endgroup\$ Commented Apr 20, 2020 at 1:40
  • \$\begingroup\$ @petStorm yep, same pneumonic but different binary encoding. Not sure I'd want to try the 4004 instruction set for any non-trivial challenges though. The minimalism of it seems like it may end up actually being less golfy than say the x86 [citation needed]. :) \$\endgroup\$
    – 640KB
    Commented Aug 14, 2020 at 14:36
  • 1
    \$\begingroup\$ @petStorm also there's a 0 byte answer for this on the Altair 8800. "Input in memory address 0000, 'RESET', 'EXAMINE' and result is in D0 on the front panel". No CPU instructions ever run! \$\endgroup\$
    – 640KB
    Commented Aug 14, 2020 at 14:38
  • \$\begingroup\$ @petStorm Yeah, I just mean if you needed to write the equivalent of say, lodsb (1 byte in x86), how many bytes would it take in 4004? Or loop, cmpsb, and of course mul, div! All do-able of course, I'd just think that if you needed some of those types of instructions you'd (ironically) end up using up a lot more bytes doing it... or not. It'd certainly be fun to try! \$\endgroup\$
    – 640KB
    Commented Aug 14, 2020 at 15:21
10
\$\begingroup\$

05AB1E, 1 byte

È

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ É is a better choice, in my personal opinion; kidding. \$\endgroup\$ Commented Mar 21, 2017 at 14:17
  • 7
    \$\begingroup\$ I assume É returns a % 2 == 1. \$\endgroup\$ Commented Mar 26, 2017 at 19:07
  • 3
    \$\begingroup\$ It's only self-explanatory if you already know the operator \$\endgroup\$
    – MilkyWay90
    Commented Feb 12, 2019 at 0:15
10
\$\begingroup\$

Pyth, 3 2 bytes

I did it. I golfed the ungolfable. For once, it's a non-trivial solution that managed to get that last byte!

!F

Truthy on even values (not including 0, but that's not positive so...).

Explanation:

!    Not
 FQQ Applied to the input (first Q) Q times

For example, !!2 = !0 = 1, and !!!3 = !!0 = !1 = 0

I'll keep my library of 3-byte solutions here below.

"There's another answer with multiple 3-byte solutions, but it's far from complete. Let's add a couple more:

@U2

Indexes into the list [0,1] modularly, giving truthy values on odd input.

}2P

Is 2 in the prime factorization of the input? (Truthy on even)

ti2

Is the GCD of 2 and the input 2? (Truthy on even)

gx1

does XOR-ing the input with 1 not decrease it? (Truthy on even)

q_F

Basically Q == Q*-1^Q where Q is the input, but done through a loop. (Truthy on even)

_FI

Same as above.

g^_

Translates to Q <= -Q^Q (Truthy on even)

Note that any of the above solutions involving g will work with < for flipped truthy-falsiness.)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Yes, that's rather clever :) \$\endgroup\$ Commented Mar 26, 2017 at 5:05
10
+100
\$\begingroup\$

BitCycle, 19 17 16 15 bytes

?ABv
 // <
!+\<

Try it online!

Argh, I feel like there's a 18 byte solution floating just out of reach :( Haha! -2 bytes by using a + to redirect bits coming from different directions.

Explanation:

?ABv   Feed unary input into the main loop
 /     Every loop, two bits will be removed from the input
 +\<   By the \ and /s each
       When we reach the point where there is either one or no bits of input left
 // <  If one, it will reflect off all three /\s and turn west at the +
!+\    And then output, otherwise the program ends since no more bits are moving
\$\endgroup\$
0
9
\$\begingroup\$

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!

\$\endgroup\$
6
  • \$\begingroup\$ You know, you can just copy the full answer (with the necessary formatting for the trailing linefeed) from TIO. \$\endgroup\$ Commented Mar 21, 2017 at 10:50
  • \$\begingroup\$ @MartinEnder No, I didn't know. \$\endgroup\$
    – Neil
    Commented Mar 21, 2017 at 10:52
  • \$\begingroup\$ It's the second-to-last snippet when you generate the permalink. \$\endgroup\$ Commented Mar 21, 2017 at 10:54
  • \$\begingroup\$ Oh, it's a whole snippet? I just see the title line. \$\endgroup\$
    – Neil
    Commented Mar 21, 2017 at 10:59
  • \$\begingroup\$ @Neil if you click in the snippet, it will expand it and you'll see the body \$\endgroup\$
    – Dada
    Commented Mar 21, 2017 at 11:01
8
\$\begingroup\$

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!

\$\endgroup\$
7
  • \$\begingroup\$ Woah, that seems really clever. I've never seen an answer like this before! How do you call this? \$\endgroup\$
    – DJMcMayhem
    Commented Mar 21, 2017 at 18:16
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Mar 21, 2017 at 21:03
  • \$\begingroup\$ I don't think this actually qualifies, as the code would just be compiled into a return 1 or return 0. Running the same compiled code again would never yield a different result, it's not a function in this way. Closer to a constant. \$\endgroup\$ Commented Mar 26, 2017 at 7:03
  • \$\begingroup\$ @DrunkenCodeMonkey the evaluation time is irrelevant. What matters is that I can pass arguments to the construct (provide input), and it will give back results (return output). From your point of view, no function would be qualifiable, as without a main()-like construct, the program would also just be compiled to a return 0, or even fail to compile at all. This contradicts the meta post I linked to in this answer. \$\endgroup\$ Commented Mar 27, 2017 at 16:28
  • 2
    \$\begingroup\$ C++ lambda function saves 3 bytes [](int x){return x%2;} Try it online \$\endgroup\$
    – jdt
    Commented May 17, 2017 at 7:40
8
\$\begingroup\$

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      # Gets input and adds 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 jumps 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.

\$\endgroup\$
8
  • \$\begingroup\$ 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? \$\endgroup\$
    – seshoumara
    Commented Mar 21, 2017 at 17:16
  • \$\begingroup\$ @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. \$\endgroup\$
    – steenbergh
    Commented Mar 21, 2017 at 18:47
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 23, 2017 at 0:06
  • 2
    \$\begingroup\$ @Blacksilver The real challenge, I think, would be to make a Spacechem answer! \$\endgroup\$ Commented Mar 29, 2017 at 6:35
  • 1
    \$\begingroup\$ I have implemented a TIS emulator for TIO, so you can now try it online! \$\endgroup\$
    – Phlarx
    Commented May 2, 2018 at 20:03
8
\$\begingroup\$

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 (two extra bytes!) 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)

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

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;
\$\endgroup\$
5
  • \$\begingroup\$ @obarakon Not in C#, see this answer on meta. Basically if (1) does not compile. \$\endgroup\$ Commented Mar 23, 2017 at 9:01
  • \$\begingroup\$ there is no if (1) in your code? \$\endgroup\$
    – YOU
    Commented Mar 24, 2017 at 7:32
  • 1
    \$\begingroup\$ @YOU Correct, read the meta post to understand what I meant by that. \$\endgroup\$ Commented Mar 24, 2017 at 8:50
  • 3
    \$\begingroup\$ @YOU, the accepted definition (on this site) of a truthy/falsey value is: If if (x) evaluates to true then x is a truthy value. If it evaluates to false then it's false. So, in pseudo code: if x, disp(true), else disp(false). If that fails to compile, then x can't be used. In MATLAB and several other languages, anything that non-zero is considered true, while 0 and false are considered false. So the string Hello is a truthy value in MATLAB. However, some languages requires the value to be a boolean value (the case here), thus it must be converted to a boolean, using <1. \$\endgroup\$ Commented Mar 24, 2017 at 8:53
  • \$\begingroup\$ I see. thanks for the explanations. \$\endgroup\$
    – YOU
    Commented Mar 24, 2017 at 11:50
7
\$\begingroup\$

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
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Not a builtin, but there is a 2-byte solution. \$\endgroup\$
    – Steven H.
    Commented Mar 26, 2017 at 3:32
7
\$\begingroup\$

Bash + bc, 21 14 11 9 bytes

bc<<<$1%2

Reads command-line input, expands the value into the string with the mod operation, and pipes the string to bc for calculation. Outputs 1 for odd, 0 for even.

Test cases:

(Input):(Output)
1:1
2:0
16384:0
99999999:1

Edit: saved 7 bytes thanks to @ais523
Edit 2: saved another 3 bytes thanks to @Dennis
Edit 3: saved another two thanks to @Dennis

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Welcome to the site! \$\endgroup\$
    – DJMcMayhem
    Commented Mar 24, 2017 at 17:52
  • \$\begingroup\$ Perhaps you could take input from a command-line argument to bash (such as $1) rather than spending bytes reading it from stdin? \$\endgroup\$
    – user62131
    Commented Mar 26, 2017 at 3:25
  • \$\begingroup\$ @ais523: Great suggestion! I should have thought about doing it in a script instead of just on the command line. \$\endgroup\$ Commented Mar 26, 2017 at 4:04
  • \$\begingroup\$ You can shorten this to bc<<<$1%2. \$\endgroup\$
    – Dennis
    Commented Mar 26, 2017 at 14:38
  • 1
    \$\begingroup\$ You don't need the quotes. Neither digits nor % require them. \$\endgroup\$
    – Dennis
    Commented Mar 27, 2017 at 3:17
7
\$\begingroup\$

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 if the input is odd).

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.

\$\endgroup\$
6
\$\begingroup\$

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.)

\$\endgroup\$
1
  • 2
    \$\begingroup\$ All these languages seem a bit of a cheat for these questions lol \$\endgroup\$ Commented Mar 26, 2017 at 6:59
6
\$\begingroup\$

Pure Bash, 8

  • 3 bytes saved thanks to @Dennis
(($1%2))

Input given as a command-line parameter to this function f. Output returned as a shell return value - display with echo $?

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

Alice, 7 bytes

1\@
oAi

Try it online!

Prints 0 for even inputs and 1 for odd inputs.

Explanation

This is structurally similar to my addition program, but the flipped mirror subtly changes the control flow:

1    Push 1.
\    Reflect northeast. Switch to Ordinal.
     Bounce off the boundary, move southeast.
i    Read all input as a string.
     Bounce off the corner, move back northwest.
\    Reflect south. Switch to Cardinal.
A    Implicitly convert input string to integer. Compute bitwise AND with 1.
     Wrap around to the first line.
\    Reflect northwes. Switch to Ordinal.
     Bounce off the boundary, move southwest.
o    Implicitly convert result to string and print it.
     Bounce off the corner, move back northeast.
\    Reflect east. Switch to Cardinal.
@    Terminate the program.
\$\endgroup\$
1
2 3 4 5
9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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