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

263 Answers 263

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

Scala, 14 Bytes

(x:Int)=>x%2<1
\$\endgroup\$
0
2
\$\begingroup\$

Acc!!, 43 bytes

N
Count i while _/10 {
N-_%2*2
}
Write _+41

Because of quirks of the input mechanism in Acc!!, the input number (given on stdin) has to be terminated with a signal value--in this case, a tab character. The code outputs 2 if the number is even, 0 if it is odd.

Explanation

# Read a character's ASCII value into the accumulator
N
# Loop while accumulator intdiv 10 is greater than 0 (i.e. acc >= 10)
Count i while _/10 {
    # Read another ASCII value, subtract (current acc % 2) * 2, and store back to acc
    N-_%2*2
}
# At the end of the loop, we know we just read a tab character (ASCII 9). This means the
# acc value is 9 if the previous digit had an even ASCII value, or 7 if it was odd. We
# add 41 to convert to the ASCII codes of 2 and 0, respectively, and write to stdout.
Write _+41
\$\endgroup\$
1
  • \$\begingroup\$ 40 bytes by abusing interpreter bugs; outputs 1 when number is odd and no output when number is even. A unary input version is only 34 bytes \$\endgroup\$ Commented May 8 at 12:06
2
\$\begingroup\$

PHP, 14 bytes

<?=$argv[1]&1;

When I test for odd or even, I only look at the first bit and not % the whole integer.

\$\endgroup\$
2
\$\begingroup\$

Clojure, 15 bytes

#(= 0(rem % 2))

Ignoring the obvious built-ins, this is probably as short as it gets.

Checks if the argument divided by 2 equals 0. Nothing fancy. Returns true for even numbers, false for odd.

Beaten by brainfuck!

\$\endgroup\$
2
\$\begingroup\$

Klein, 18 17 16 + 3 bytes, (non-competing)

Uses the 001 topology. Embedded in a Klein Bottle

1(/+@
-+)-($?/:1

Explanation

Here is a gif of it running on 6:

enter image description here

The general way this works is it continually decrements the input down to zero each time multiplying a saved value by -1. That way the saved value will be negative if odd and positive if even.

Setup

Right as the program begins running it does its set up

1(

This puts a 1 on the scope. This is the number we will multiply by -1 to keep track of the parity.

We then use a mirror to deflect the ip of the top of the screen. Since we are on a Klein Bottle and not a Torus this deflection will not only bring us to the bottom but also flip our horizontal coordinate. The ip will move upwards through mostly blank space until it hits another mirror. This mirror puts it in the main loop.

Main Loop

In the main loop we make a duplicate of the input and decrement it by one, multiply the scoped value by -1 using )-( and then we switch the copied version of the counter with the original, we copied it earlier because ? our conditional jump consumes a value. Since ? skips the mirror we will run until our counter is zero.

However since we are checking the copy of the counter, we will actually exit when we hit -1. This is important because it saves us from having to make a value later.

Cleanup

Once we hit zero we are deflected again but the mirror. This sends us over the top of the screen. Since we are on a Klein Bottle this twists us back around and causes the ip to collide with the ) used in part of the code. This is convenient because it recalls the scoped value to the stack. We then get deflected by one of the mirrors from before. Lastly we add the two values, the counter and the saved value. The counter will always be -1 so we are essentially just subtracting 1 from the saved value. The saved value will be either 1 or -1 so our result is either -2 or 0. Then we end and output using @.

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

newline 19 bytes

g\n0\n/\n[\nd\n]

and the number 2

\$\endgroup\$
2
\$\begingroup\$

Fortran 95,  31  28 bytes

Thanks to @georgewatson for saving three bytes!

function h(i)
h=mod(i,2)
end

Returns 0 if even, 1 if odd.

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Since input is always a positive integer, you could save 3 bytes by using mod. \$\endgroup\$ Commented Feb 1, 2018 at 10:18
  • \$\begingroup\$ @georgewatson Thanks! \$\endgroup\$
    – Steadybox
    Commented Feb 1, 2018 at 14:19
  • \$\begingroup\$ 27 bytes \$\endgroup\$
    – roblogic
    Commented Oct 6, 2022 at 11:04
2
\$\begingroup\$

Whitespace, 30 bytes

[S S S T    S N
_Push_2][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_number][T    T   T   _Retrieve][S N
T   _Swap_top_two][T    S T T   _Modulo][T  N
S T _Output]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Outputs 0 for even, 1 for odd.

Try it online.

Explanation (with 5 as input):

Command    Explanation             Stack      Heap     STDIN    STDOUT

SSSTSN     Push 2                  [2]        {}
SNS        Duplicate top (2)       [2,2]      {}
SNS        Duplicate top (2)       [2,2,2]    {}
TNTT       Read STDIN as number    [2,2]      {2:5}    5
TTT        Retrieve                [2,5]      {2:5}
SNT        Swap top two            [5,2]      {2:5}
TSTT       Modulo                  [1]        {2:5}
TNST       Output top as number    []         {2:5}             1
\$\endgroup\$
2
\$\begingroup\$

Dodos, 13 bytes

	main dip dip

Try it online!

This program is composed by a single main function which decrements twice its number and then recurses. Due to how Dodos works, instead of infinitely recursing the first call that would go to a negative number will return its argument instead, which will be either 0 or 1.

\$\endgroup\$
1
2
\$\begingroup\$

Python 2, 13 bytes

lambda n:~n&1

Try it online!

No shorter than the other non-REPL Python answers, but uses slightly different logic. Takes the bitwise complement of the input number (-x-1) and performs a BITWISE AND on it. Returns 1 if the complement is odd, and 0 if the complement is even - and therefore returns 1/0 if the original number was even/odd.

(Could be shortened by 1 byte by removing the complement ~ if 0=True and 1=False is allowable.)

\$\endgroup\$
2
\$\begingroup\$

BitCycle, 22 bytes

This program takes input on the command-line in unary; it outputs 1 for odd, nothing for even. You can also specify the -u flag and give input in decimal, in which case the output is 1 for odd, 0 for even.

?v
v<  <
A\\B^
>/\
  !

Explanation

Here's a slightly ungolfed version in action (the same logic with extra space added for clarity):

The program in action. Input: 5; output: 1 (for "odd")

The input bits come in at the source ? and are routed into the A collector. Once the whole input is in there, bits are emitted one at a time to the right. The two splitters \\ send the first two bits downward, while the remainder go into the B collector. (Splitters deactivate after the first time a bit hits them, so the second bit passes through the deactivated first splitter and is reflected by the second one.)

The second bit goes down, is reflected rightward by \, and goes off the playfield. Meanwhile, the first bit is reflected leftward by / and immediately sent rightward again by >. It passes through the two deactivated splitters and goes off the playfield. Finally, if there are any bits still in the B collector, they are now cycled around back to A. When the collectors come open, the splitters return to their original state, and the loop continues until there are less than two bits left.

If the number was even, there will be no bits left, in which case the program terminates without output. If the number was odd, there is a single bit left in A. The splitters \ and / send it down and left to the >, which sends it to the right. It goes back through the deactivated / and hits the bottom-right \. The latter has not been deactivated this time because there wasn't a second bit. So it reflects the single bit downward into the sink !, which outputs it.

\$\endgroup\$
2
\$\begingroup\$

INTERCAL, 45 bytes

DOWRITEIN:1PLEASE:1<-:1~#1DOREADOUT:1DOGIVEUP

Try it online!

Prints 1 if the input is odd and 0 if the input is even.

...except this being the wonderful Compiler Language With No Pronounceable Acronym, 1 is printed as newline-I-newline while 0 is printed as underscore-newline-newline, and input has to have the individual digits spelled out in one of several natural languages or a mix thereof (such that the third test case, 16384, is just as well English ONE SIX THREE EIGHT FOUR as Basque-Latin-Georgian-Tagalog-Kwakiutl BAT SEX SAMI WALO MU). Also, I'm not actually sure which INTERCAL dialect this is.

DO WRITE IN :1      Take a line of input and store the value in the variable :1.
PLEASE :1<-:1~#1    Politely reassign :1 to be the first bit of its old value.
DO READ OUT :1      Print :1 in "butchered Roman numerals".
DO GIVE UP          End the program.
\$\endgroup\$
2
\$\begingroup\$

ZX80 (4K ROM) 23 tokenised BASIC bytes

 1 INPUT A
 2 PRINT A;":"; NOT A AND 1
 3 CONTINUE

This is a very simple solution as in Sinclair ZX80 BASIC, PRINT 111 AND 1 will produce 1 (and therefore any odd number entered will produce 1 because in binary for any odd positive integer the zeroth bit is always set, so PRINT 11 AND 1 will do 00001011 & 00000001 at the processor level more or less) - if we assume even is true then we can use NOT to invert the value, therefor NOT 111 AND 1 will produce 0 or our false value.

Using the CONTINUE command will continue the symbolic listing from line 1. You may also use RUN but both are equal in the basic tokens used.

ZX80 (4K ROM) 16 tokenised BASIC bytes

If we assume that odd is our true value then we can remove some of the logic as follows (also saving bytes):

 1 INPUT A
 2 PRINT A;":";A AND 1
 3 RUN

There is one caveat; by using ZX80 BASIC, you may only enter 16-bit wide signed integers, so the range is -32768 to +32767 inclusive.

The same logic will work in Commodore BASIC (C64/VIC-20) so whilst both of the above will work, you may condense it into one line like 0inputa:printa":"aand1:goto.

ZX80 4K ROM edition

\$\endgroup\$
2
\$\begingroup\$

Keg, 2 3 bytes

^2%

Last number outputted will be 1 if the number is odd, and 0 if it's even

Edit: Fixed for latest version

Try it Online!

\$\endgroup\$
5
  • \$\begingroup\$ This seems to be for an old version, before 2019-08-13. Unfortunately the unconditional implicit input used by this code does not exist in current version. \$\endgroup\$
    – manatwork
    Commented Aug 20, 2019 at 15:52
  • \$\begingroup\$ Fixed, don't know why that got removed \$\endgroup\$
    – EdgyNerd
    Commented Aug 20, 2019 at 15:54
  • \$\begingroup\$ Uhm… You probably mean ^2%, thinking to multidigit numbers. \$\endgroup\$
    – manatwork
    Commented Aug 20, 2019 at 15:55
  • \$\begingroup\$ Fixed again, oops \$\endgroup\$
    – EdgyNerd
    Commented Aug 20, 2019 at 15:58
  • \$\begingroup\$ 2% works again now. \$\endgroup\$
    – lyxal
    Commented Nov 15, 2019 at 21:33
2
\$\begingroup\$

Cascade, 7 5 bytes

#2&
%

Found a 2 bytes shorter solution by abusing wrapping Try it online!

\$\endgroup\$
2
\$\begingroup\$

Toi, 6 bytes

(r[rr]

Try it online!

Toi is a language that only knows sets. The memory is a set S that starts as the empty set. The input number can be given as a von Neumann ordinal, constructed using "ua"*n, or alternatively the input number can be represented by the nesting level using "u"*n. u nests the context S, and a changes S to \$S \cup \{t \mid t \in s, s \in S\}\$ (from the esolangs wiki article).

( cond [ stuff ] is a while loop that performs stuff while applying cond on S yields a non-empty set. The commands in cond are unapplied before executing into stuff.

r changes S to \$\{t \mid t \in s, s \in S\}\$ essentially removes a layer of nesting. This effectively decrements the number represented by S by 1.

So, the meaning of ( r [ rr ] is the following: while r on S is non-empty (i.e. while S-1 is not 0), perform rr (decrement S twice).

The parity is left on S, \$\{\{\}\}\$ if the input is odd, and \$\{\}\$ otherwise.

\$\endgroup\$
2
\$\begingroup\$

RPL, 4 bytes

2MOD

Plain answer in vanilla RPL, for posterity and completeness of this thread.

As often with RPL, one byte is saved in the source code by removing a space between a number and a command. I assume this is rarely observed in Forth.

\$\endgroup\$
2
\$\begingroup\$

Poetic, 190 bytes

although i agree i,a person,i was dismissive about a hell,i am not anarchic
i repeat:i know theres never a hell i am doomed to
actually,it seems a bit of a fraud,a lie,if He gives a man he|l

Try it online!

Input is in decimal. Output is an Unexpected EOF error for even inputs, and a Mismatched IF/EIF error for odd inputs. It takes forever to actually execute, though.

(Doesn't work for 0, but the question only specified positive inputs.)

\$\endgroup\$
2
\$\begingroup\$

Python 3, 12 bytes

lambda n:n&1

Outputs 1 for odd, 0 for even.

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 1 byte

É

Try it online!

Explanation

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

Pyramid Scheme, 221 199 bytes

   ^       ^ ^
  / \     /l\-
 /set\   /oop\
^-----^ ^-----^
-    ^- -^   / \
    ^-  /*\ /set\
   /#\ ^---^-----^
  ^---/-\  -    /-\
 /l\ ^---^     ^---^
/ine\-  /1\    -  /2\
-----   ---       ---

Try it online!

Outputs 0 for even and 1 for odd.

Pyramid Scheme has no modulus, no integer division, and no bitwise operators. The best approach I could conceive was repeatedly subtracting two from the input until either it or its predecessor is zero, then printing the final value.

This program translates rather easily to true Scheme. I have to say, that's my favorite part of this language—it's very nearly a Scheme dialect in its own right, despite being a joke!

(define n (read))
(do ()
    ((= 0 (* n (- n 1))))
  (set! n (- n 2)))
(display n)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

MAWP, 9 bytes

@!!2P2WA:

Try it!

Just a homemade modulo function. Outputs 1 if odd and 0 if even

\$\endgroup\$
6
  • \$\begingroup\$ That's unfair! :( The continous addition of built-ins here and there makes it much more golfier than 1+ (which cannot be updated, otherwise it's no longer 1+!) \$\endgroup\$ Commented Aug 11, 2020 at 9:05
  • \$\begingroup\$ @HighlyRadioactive I mean, the only builtin thats really beneficial is the input method - the rest is the modulo function !!xPxWA (where x is the number by which to modulo) that i invented :D \$\endgroup\$
    – Dion
    Commented Aug 11, 2020 at 9:15
  • \$\begingroup\$ Alright, fair enough. I try to [compete with MAWP] with 1+, because both of them are easy-to-use "Turing-tarpit-ish" languages. \$\endgroup\$ Commented Aug 11, 2020 at 9:21
  • \$\begingroup\$ @HighlyRadioactive challenge accepted! :D \$\endgroup\$
    – Dion
    Commented Aug 11, 2020 at 9:22
  • \$\begingroup\$ :D You should keep a "MAWP answer list" somewhere... \$\endgroup\$ Commented Aug 11, 2020 at 9:26
2
\$\begingroup\$

Google Sheets, 9 bytes

=MOD(A1,2

Google Sheets auto closes parenthesis. Its pretty self explanatory, it just does modulo 2 on the input (A1).

\$\endgroup\$
2
\$\begingroup\$

Aceto, 6 bytes.

%2
rip

ri reads a string and casts it to an integer, 2% does modulo 2, and p prints. 0 stands for even and 1 for odd in the printed result.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is very likely the theoretical minimum. \$\endgroup\$
    – L3viathan
    Commented May 8, 2017 at 8:31
  • 2
    \$\begingroup\$ rip Aceto, postdated the challenge \$\endgroup\$ Commented May 8, 2017 at 8:32
  • 1
    \$\begingroup\$ :) @L3viathan is indeed the theoretical minimum. \$\endgroup\$ Commented May 8, 2017 at 8:33
2
\$\begingroup\$

17, 40 bytes

1 for odd, 0 for even. It takes input until a newline is entered and then prints mod 2 of last byte.

0{I : a == 0 @}1{0 @ 2 % $$}777{0 0 @}
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to the site! We allow languages to be created after the challenge so no need to bother with "not competing". \$\endgroup\$
    – Wheat Wizard
    Commented Feb 4, 2018 at 20:48
2
\$\begingroup\$

sed, 5 bytes

/0$/d

Try it online!

Takes the input as a binary string. sed does not have truthy/falsey values, so I am defining truthy as a non-empty output and falsey as an empty output. As per this meta post, this is acceptable since these sets are non-overlapping.

For the cost of one byte, we can instead output by exit code:

/0$/q1

The following also works if input is taken as a binary list of digits, linefeed separated, but I don't think that's an acceptable input method.

$!d
\$\endgroup\$
2
\$\begingroup\$

Factor, 5 4 bytes

odd?

Try it online!

Outputs t if odd, f if even.

I feel a bit guilty doing this (and also stupid after Bubbler's suggestion).

\$\endgroup\$
1
  • 1
    \$\begingroup\$ odd? is one byte shorter. \$\endgroup\$
    – Bubbler
    Commented Mar 17, 2021 at 23:41
2
\$\begingroup\$

Add++, 5 bytes

?%2
o

Try it online!

Simple?

\$\endgroup\$
2
\$\begingroup\$

x86_64 Linux machine language, 5 bytes

0:       97                      xchg   %edi,%eax
1:       83 e0 01                and    $0x1,%eax
4:       c3                      retq

To try it, compile and run the following C program

#include<stdio.h>
const char f[]="\x97\x83\xe0\1\xc3";
int main(){
  for( int i = 0; i < 10; i++ ) {
    printf("%d %d\n", i, ((int(*)(int))f)(i) );
  }
}

Try it online!

EDIT: Fixed TIO link.

\$\endgroup\$
2
\$\begingroup\$

TypeScript's Type System, No Ignore, 400 41 Bytes

type F<N>=N extends[...any,0|2|4|6|8]?1:0

TypeScript Playground

  • Use Jacob's suggestion of checking the last number.

Usage

// input is taken as an array (12 -> [1, 2])
type Test = F<[1,2]> // 1, the number is even

type Test2 = F<[1,1]> // 0, the number is odd.

The program checks if the last digit in the array is an even number.

\$\endgroup\$
3
  • \$\begingroup\$ 129 bytes or 54 bytes by taking input in unary \$\endgroup\$ Commented May 3, 2023 at 2:45
  • 1
    \$\begingroup\$ BTW both versions I sent can have a few bytes saved by replacing L["length"]extends N with your L extends{length:N} \$\endgroup\$ Commented May 3, 2023 at 3:24
  • 1
    \$\begingroup\$ Omg I’m pretty sure it’s shorter to just…check if the last digit is 0|2|4|6|8 lol! I’m on my phone so I can’t use the playground but I think type X<N>=N extends[...any,0|2|4|6|8]?1:0 works (taking numeric input as list of digits) \$\endgroup\$ Commented May 3, 2023 at 3:39
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.