25
\$\begingroup\$

Task

Given a non-negative number, check if it's odd or even. In case it's even, output that number. Otherwise, throw any exception/error that your language supports, and stop the program.

Example with Python

Input: 1
Output:

Traceback (most recent call last):
  File ".code.tio", line 1, in <module>
    IfYouWantThenThrowThis
NameError: name 'IfYouWantThenThrowThis' is not defined

Another example

Input: 2
Output: 2

Rules

  • This is , so the answer with shortest bytes wins.
  • These loopholes are, obviously, forbidden.
  • Standard code-golf rules apply.
  • Please specify the language you are using and the amount of bytes.
  • It would be great if you would put a link to a sandbox where your code can be ran in action, such as TIO.
  • Explaining your code is very welcomed.

LEADERBOARD

<script>var QUESTION_ID=229052,OVERRIDE_USER=0;</script><style>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}</script><link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

\$\endgroup\$
11
  • 11
    \$\begingroup\$ I would highly recommend you start posting your challenge ideas to the Sandbox first to get feedback \$\endgroup\$
    – pxeger
    Jun 5 at 19:32
  • 1
    \$\begingroup\$ related \$\endgroup\$
    – 640KB
    Jun 6 at 0:36
  • 3
    \$\begingroup\$ I would advise against adding a leaderboard to your challenge, especially one that has to be updated manually, since it takes up space and will likely become outdated soon. \$\endgroup\$
    – rues
    Jun 6 at 16:36
  • 2
    \$\begingroup\$ If you really want a leaderboard, I would recommend using the leaderboard stack snippet instead. It'll update automatically, so you won't have to edit your question every time someone posts an answer that makes it to the leaderboard. \$\endgroup\$
    – rues
    Jun 6 at 21:05
  • 5
    \$\begingroup\$ I would also advise against having any kind of leaderboard. My answer may be the shortest (and the earliest to be that short), but that doesn't make it any more deserving of attention than any other answer. Personally, I found the Hexagony answer really interesting, along with a number of other answers. Instead, I suggest that people just sort by active - you'll find the creative answers that have been "buried" due to votes that way :) \$\endgroup\$ Jun 7 at 2:10

65 Answers 65

31
\$\begingroup\$

Python 2, 16 bytes

lambda n:n<<n%-2

Try it online!

The expression n%-2 equals 0 for even n and -1 for odd n. Bit-shifting n by 0 positions leaves it unchanged, but for -1 positions it gives an error for "negative shift count".

\$\endgroup\$
25
\$\begingroup\$

Jelly, 3 bytes

MḂ¡

Try it online! (even) and Try it online! (odd)

How it works

M is an atom meaning "Given a list, yield the indices of that maximal elements". Now, typically, when given integer arguments to its array functions, Jelly promotes them to either a range, to digits, or just wraps it. Unfortunately, (I'm guessing due to M's age - it was one of the earliest builtins in Jelly), M doesn't do this, and throws an error as it can't iterate over an integer.

How the code actually works:

MḂ¡ - Main link. Takes N on the left
 Ḃ  - Bit; Calculate N % 2
  ¡ - Do the following a number of times equal to N % 2:
M   -   Run the M builtin on N

If the input N is even, then yields 0 and ¡ runs M on N 0 times i.e. an identity function.

If the input is odd, then yields 1 and ¡ runs M once, which is enough to error it

\$\endgroup\$
22
\$\begingroup\$

Hexagony, 13 bytes

?#\.@!:.!_@\|

Try it online!

Expanded: (Made using Hexagony Colorer)

Hexagony Colorer Map

This code is built around Hexagony's # operator. Hexagony initializes with 6 IP's, 1 in each corner of the code box, with the 0th one, the one in the top left, being active in the beginning. The # operator takes the value of the current memory cell mod 6, and then sets the corresponding IP as the active one. So making an even/odd checker is a matter of using the # operator and then having IP's 1,3, and 5 perform the 'odd' action, and IP's 0,2, and 4 perform the 'even' action. The consequence of doing it this way is that there are 6 separate paths that each need to be mapped to the correct endpoint, hence the mess of paths. In this case, the odd action is : (attempt to divide two non-existent values, resulting in a divide by zero error) and the even action is !@ (print and terminate). To make it hopefully a bit more readable, here's a very low-tech drawing of the paths:

Hand-drawn map

The paths are:

  • n%6 == 0 : Green
  • n%6 == 1 : Yellow
  • n%6 == 2 : Blue
  • n%6 == 3 Pink
  • n%6 == 4 : Orange
  • n%6 == 5 : Red

I'm pretty confident 12 bytes is possible, and potentially even shorter. Not sure if there's a better approach entirely, but with this method, it seems just about brute-force-able. It seems it should only require ?,#, no more than 3 each of @,!, and :, and some control flow characters.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Hand-drawn Hexagony execution map is a great evolution path from hand-drawn circles \$\endgroup\$ Jun 7 at 13:10
16
\$\begingroup\$

x86 Machine Code, 5 bytes

A8 01 74 01 F4

Takes the integer value of your choice in the EAX register, halts the CPU if the number is odd, or continues execution harmlessly if the number is even.

Ungolfed assembly language mnemonics:

A8 01         test   al, 1
74 01         jz     IsEven
F4            hlt
          IsEven:

The first two instructions (test+jz) are the fastest and smallest way to check whether an integer value is even or odd in x86 machine code. The reason they work is hopefully obvious: for binary numbers, the least-significant bit (bit 0) is only set if the number is odd (for even numbers, the least-significant bit is clear). Therefore, testing the least-significant bit and seeing if it is non-zero is the easiest, simplest, smallest, and fastest way to see whether a number is even.

Here, I've used jz to jump if the zero flag (ZF) is set—i.e., if the bit we tested (bit 0) was zero, which means that it jumps if the number was even. Note that it jumps over the halt (hlt) instruction if the input value was even. If the input value was odd, then execution falls through the jump, and ends up halting the CPU.

If you don't like hlt because you don't think that counts as throwing an exception/error, then replace it with an int 3 instruction, which is also only 1 byte (0xCC), and thus doesn't change the overall code size (5 bytes). The int 3 instruction is the trap to a debugger.

The only way you could really argue that this code is cheating is that it doesn't "output" that number. I'd say it does: it allows execution to continue past the point where that number was generated, which is a lot like outputting it. You don't get any output for odd inputs; you can only get output for even inputs. Besides that, I think this is allowed by many, many different agreed-upon input/output methods.


x86 Machine Code, 6 bytes (non-competing)

A division by 0 is another obvious solution, but it doesn't save any bytes. Even if you are willing to allow clobbering the input value, in order to arrange for a division by zero, you have to negate somewhere (either the original value, or the isolated LSB), and that requires an extra instruction (either XORing with 1, or a NOT), which means 2 extra bytes.

A8 01         test   al, 1
34 01         xor    al, 1
F6 F0         div    al

That's 6 bytes, and I'm not even sure that I can figure out how to justify this clobbering of the original input value as being consistent with the requirements of the challenge to "output" the value.

To avoid clobbering, there are a few different options. For example, we can stipulate that the input is taken in a different register (say, ECX). But this means that we can't use the short "implied accumulator" encoding of test and xor, so it costs us at least two bytes. (We could use not with the full register before the test to invert the bits, which is encoded in only 2 bytes, but that defeats the point, which is to avoid clobbering the input.) Or, we could push and pop the input, but that also costs two extra bytes (one for each, push and pop). Maybe I'm missing something obvious, but I'm not seeing a better solution here.

\$\endgroup\$
10
  • \$\begingroup\$ It could be argued that the 2 byte test al,1 (where output is in ax if even and nz flag if odd) would meet the requirements, since testing for a flag is a very standard way in machine code to signify an "exception/error". \$\endgroup\$
    – 640KB
    Jun 6 at 4:31
  • 5
    \$\begingroup\$ You can save a byte by switching the jz isEven to a jnz -3 : that is, jumping into the middle of the test al, 1 instruction. The byte sequence 01 74 01 does not correspond to a valid x86 instruction encoding so you will get SIGILL. \$\endgroup\$
    – Sisyphus
    Jun 6 at 6:58
  • \$\begingroup\$ oh my god what the is going on here \$\endgroup\$ Jun 6 at 8:20
  • \$\begingroup\$ If possible, please make a link to the language origin/wiki page, and very much preferably an online implementation of this. If second is impossible, then tell me \$\endgroup\$ Jun 6 at 10:34
  • 2
    \$\begingroup\$ @Leopard What is a "language origin/wiki page"? x86 is an extremely popular microprocessor architecture originally developed by Intel. I call it "machine code" because of weird code-golf rules about byte counting. Normally, people would just call this assembly, but that would apparently mean that I have to count the ASCII characters in the assembly mnemonics, which is ridiculous. You'll note that I usually include a link to "Try It Online" for my assembly answers, but that's not really possible here. You won't be able to tell that the CPU is halted. I feel like the explanation is sufficient. \$\endgroup\$
    – Cody Gray
    Jun 8 at 8:47
12
\$\begingroup\$

Java (JDK), 10 bytes

n->n/=~n&1

Try it online!

Explanations

This code basically divides by zero when the input number is odd or by one when it is even.

~n

The ~ character negates each bit of n because n&1 returns 0 when n is even and 1 when it's odd, but we want the opposite: 0 when odd (to make it fail) and 1 when even to return it, so ~ is the easiest way to negate the last bit.

~n&1

This is the part that reduces n to either 0 or 1. ~n&1 is not exactly the same as ~n%2 because, in Java, %2 keeps the signum of n, and since we definitely swap the signum with ~, we'd always end up with negative number, not matter what n is: if n<0 we'd get negative divided by positive, and if n>=0, we'd get positive divided by negative.

We want to divide by 0 or by 1, nothing else. Only &1 can guarantee that. No matter what, the operator priority will first evaluate ~n so no parenthesis are required.

/=

This bit is weird. Why do we do divide and assign, instead of just dividing? Technically, n/~n&1 will be parsed as x=n/~n then x&1. This is not the behavior we want: n/~n is always equal to 0. What we want is to have n/(~n&1). It could work well, but the whole answer would be n->n/(~n&1). The /= operator is a shortcut to that as it evaluates the right-hand side entirely, so we can get rid of parenthesis, gaining one byte. Assigning is a side effect we can live with.

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

MATLAB/Octave, 17 13 12 bytes

-4 bytes thanks to Sisyphus

@(x)x(i^2^x)

Try it online!
Anonymous function. Throws indexing error for odd numbers.

This function returns element from input at index i^2^x = (-1)^x, so

  • at index 1 for even numbers (which is input itself)
  • at index -1 for odd numbers (which is invalid index since indices in MATLAB start at 1)
\$\endgroup\$
0
9
\$\begingroup\$

Wolfram Language (Mathematica), 10 bytes

I think this uses an approach that isn't yet represented in the other answers.

–1 byte thanks to att!

#+0^I^#^2&

Try it online! Here I represents the imaginary number i. Since the square of every even number is a multiple of 4, I^#^2 equals 1 when the input is even, and so 0^I^#^2 becomes \$0^1\$ which is a perfectly nice 0 to add to the input. However, since the square of every odd number is one more than a multiple of 4, I^#^2 equals i when the input is odd, and so 0^I^#^2 becomes \$0^i\$ which throws an "Indeterminate expression " error.

first submission: 11 bytes

#+0^(-1)^#&

Try it online! Since –1 to an even power equals 1, 0^(-1)^# becomes \$0^1\$ when the input is even, which is a perfectly nice 0 to add to the input; however, since –1 to an odd power equals –1, 0^(-1)^# becomes \$0^{-1}\$ (the reciprocal of 0) when the input is odd, which throws an error.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 10 bytes \$\endgroup\$
    – att
    Jun 7 at 5:51
  • \$\begingroup\$ So clever! Thank you \$\endgroup\$ Jun 7 at 6:15
9
\$\begingroup\$

Vyxal, 2 bytes

₂ḭ

Try it Online!

-1 thanks to Aaron Miller

₂  # Is_even(n) (Vyxal has no booleans, only 0 and 1)
 ḭ # Integer division (ordinary division doesn't error on 0)
\$\endgroup\$
6
  • \$\begingroup\$ 2 bytes \$\endgroup\$ Jun 8 at 19:40
  • \$\begingroup\$ YOO 2 BYTES WHAT THE HELL \$\endgroup\$ Jun 13 at 10:08
  • \$\begingroup\$ @LeopardLGD It's because Vyxal has no booleans, only 0 and 1. \$\endgroup\$
    – emanresu A
    Jun 13 at 10:09
  • \$\begingroup\$ I see the explanation, I am just very glad and surprised for someone to finally break the 3 bytes barrier \$\endgroup\$ Jun 13 at 10:09
  • 1
    \$\begingroup\$ @LeopardLGD Vyxal's cool like that. \$\endgroup\$
    – emanresu A
    Jun 13 at 10:10
8
\$\begingroup\$

PowerShell, 31 25 14 19 bytes

-6 bytes thanks to @mazzy

param($n)$n/!($n%2)

Try it online!

Calculates the modulo of the input number and 2, implicitly converts the result to a boolean in order to negate it, then divides the input number by the negation. Inadvertently ditched the spec for a while there, sorry!

\$\endgroup\$
5
  • 2
    \$\begingroup\$ @mazzy Beautiful, can't believe I missed this. \$\endgroup\$
    – GMills
    Jun 6 at 17:28
  • 2
    \$\begingroup\$ -1 byte more \$\endgroup\$
    – mazzy
    Jun 6 at 17:29
  • 2
    \$\begingroup\$ I'm sorry. The code 1/... does not output that number. It should be "$args"/... or param($n)$n/... \$\endgroup\$
    – mazzy
    Jun 6 at 17:30
  • \$\begingroup\$ Doesn't currently conform to spec since even numbers aren't printed. \$\endgroup\$ Jun 7 at 13:20
  • \$\begingroup\$ @valisstillwithMonica fixed. \$\endgroup\$
    – GMills
    Jun 7 at 13:42
8
\$\begingroup\$

R, 20 bytes

n=scan();n+(n%%2&&a)

Try it online!

The && operator is logical AND, evaluating left to right until the result is determined. If n is even then n%%2 is 0, coerced to FALSE, and the a part of the expression is therefore not evaluated. We then output n+0, ie n.

If n is odd, then n%%2 is 1, coerced to TRUE, and we need to evaluate the a part of the expression to determine the result of n%%2&&a. Since a is undefined, this produces an error.

This strategy comes out 3 bytes shorter than Dominic's strategy with if.

\$\endgroup\$
2
  • \$\begingroup\$ (n=scan())+(n%%2&&a) same length \$\endgroup\$
    – qwr
    Jun 7 at 15:14
  • \$\begingroup\$ n=scan();n[!n%%2||a] same length \$\endgroup\$
    – pajonk
    Jun 8 at 6:28
7
\$\begingroup\$

MMIX, 12 bytes (3 instrs)

ihateodds   PBEV  $0,0F     // if(n even) goto ret;
            LDVTS $0,$0,6   // privileged instruction
0H          POP   1,0       // ret: return n

The LDVTS tries to make whatever memory page the input points to RWX in the cache, though not in the page table (if the input is one more than a multiple of 8). This is a privileged instruction for obvious reasons.

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

Python 3, 17 bytes

lambda x:[x][x%2]

Try it online!

It's very simple - construct a list with a single (zeroth) number and take an element of it with index equal to that number modulo 2. Since there is no element 1, it will obviously throw an exception on odd input.

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

PHP, 14.

die($argv[0]);

There's no need to differentiate odd and even. The criteria say odd numbers can display any error, while even ones should be displayed.

Since the criteria allow for ANY error on an even number, and die() displays an error and terminates, the input is fine as an error.

The criteria allow for even numbers to be displayed in any manner, including as an error, so again, the input is fine as an error.

But if die() isn't accepted as an error, and a genuine terminating error's required... 27 26 bytes. Sadly we can't use die() here...

echo($a=$argv[1])%2?$b:$a;

If warnings are acceptable as errors, then in the comments Matthew Anderson's suggestion to use division by zero also gives us 26 bytes:

echo($a=$argv[1])/!($a%2);
\$\endgroup\$
6
  • 1
    \$\begingroup\$ This was mine: $i/=1-$i%2; \$\endgroup\$ Jun 6 at 23:39
  • \$\begingroup\$ @MatthewAnderson Ooh, clever trick, I like it! Can't see a way to make that super short with $argv[0]. but it feels like there has to be one. \$\endgroup\$ Jun 7 at 0:48
  • \$\begingroup\$ 1/!($argv[1]%2); There you go \$\endgroup\$ Jun 7 at 23:36
  • \$\begingroup\$ @MatthewAnderson Testing with php -r 'echo 1/!($argv[1]%2);' 2 that brings it down to 21 bytes, but unfortunately it only outputs 1 for even numbers, rather than the number itself. But we can get it down to 25 with: die($a=$argv[1])/!($a%2); Division by zero is only a warning rather than an error, but that could be moot since we're using die() anyway. \$\endgroup\$ Jun 8 at 14:48
  • \$\begingroup\$ No, I'm wrong, we need to use echo, or the die() terminates it too early, so, I can't do better than 26 bytes whichever approach we take. \$\endgroup\$ Jun 8 at 15:23
6
\$\begingroup\$

Python 2, 17 bytes

lambda n:n/(~n%2)

Try it online!

thanks to @hyper-neutrino for -4 bytes

Python 3, 24 bytes

lambda n:n%2and 1/0 or n

Try it online!

\$\endgroup\$
4
  • 2
    \$\begingroup\$ i think ~-n%2 works \$\endgroup\$
    – hyper-neutrino
    Jun 5 at 18:13
  • \$\begingroup\$ Stealing from user for the second program, you can use g instead of 1/0 to get a NameError (or any other undefined variable) \$\endgroup\$
    – hyper-neutrino
    Jun 5 at 18:30
  • 2
    \$\begingroup\$ 16 bytes: lambda n:n>>n%-2 \$\endgroup\$ Jun 5 at 18:30
  • 1
    \$\begingroup\$ Improvement for your 24 bytes: remove space between 0 and or \$\endgroup\$
    – user100690
    Jun 5 at 18:40
6
\$\begingroup\$

Retina 0.8.2, 13 bytes

+`[13579]$
99

Try it online! Explanation: If the number is odd, simply keeps appending 9s until Retina eventually runs out of memory, or until TIO kills it, whichever is sooner.

If you want a more direct error, then for 21 bytes:

[13579]$
9999999999$*

Try it online! Explanation: Tries to append more than a 32-bit integer length of 9s to the odd input, which throws an OverflowException.

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

Wolfram Language (Mathematica), 13 bytes

#/Mod[#+1,2]&

Try it online!

-1 byte from @att

\$\endgroup\$
4
  • \$\begingroup\$ 13 bytes \$\endgroup\$
    – att
    Jun 5 at 20:09
  • \$\begingroup\$ #+0^(-1)^#& works for 11 bytes (and also is a new mechanism among the answers, as far as I can tell) \$\endgroup\$ Jun 6 at 18:50
  • \$\begingroup\$ @GregMartin very nice! I think that you should post this as your own answer... I want to upvote it! \$\endgroup\$
    – ZaMoC
    Jun 6 at 20:34
  • \$\begingroup\$ Cool, answer posted :) \$\endgroup\$ Jun 6 at 20:48
6
\$\begingroup\$

APL (Dyalog Unicode), 7 bytes (SBCS)

Anonymous tacit prefix function

⊢÷1-2|⊢

Try it online!

 the argument

÷ divided by

1- one minus

2| the division remainder when 2 divides

 the argument

Or in other words:$$x\over{1-\Big({x\over2}-\big\lfloor{x\over2}\big\rfloor}\Big)$$

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

Perl 5 -p, 9 bytes

$_%2&&die

Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ $[=$_%2 for 7 \$\endgroup\$
    – Sisyphus
    Jun 8 at 0:54
6
\$\begingroup\$

Japt, 6 5 bytes

Throws a TypeError an overflow error on odd numbers. Still convinced there must be a much shorter way 🤔 /v would work if JavaScript errored on division by 0.

*v ªß

Try it

*v ªß     :Implicit input of integer
*         :Multiply by
 v        :  Divisible by 2?
   ª      :Logical OR with
    ß     :A recursive call
\$\endgroup\$
5
  • \$\begingroup\$ Wow, that's indeed short \$\endgroup\$ Jun 5 at 18:15
  • 2
    \$\begingroup\$ @LeopardLGD, give it a minute and one of the other golfing languages will be along to kick my ass! \$\endgroup\$
    – Shaggy
    Jun 5 at 18:18
  • \$\begingroup\$ Your prediction was indeed correct :) \$\endgroup\$
    – hyper-neutrino
    Jun 5 at 18:18
  • \$\begingroup\$ Oh no. RIP to this! \$\endgroup\$ Jun 5 at 18:20
  • \$\begingroup\$ Not even a minute, @hyper-neutrino 😂 \$\endgroup\$
    – Shaggy
    Jun 5 at 18:21
6
\$\begingroup\$

R, 25 23 22 bytes

Edit: -2 bytes after looking at ophact's answer, and then -1 byte thanks to Robin Ryder

`if`((n=scan())%%2,,n)

Try it online!

Throws an 'argument is missing' error when n is odd and the if expression tries to read the missing expression that should be between the two commas.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ 20 bytes using && instead of if. \$\endgroup\$ Jun 7 at 8:18
  • 1
    \$\begingroup\$ n=scan();if(T[1+n%%2])n is also 23 bytes with a different error; maybe it can be shortened. \$\endgroup\$ Jun 8 at 8:03
  • 1
    \$\begingroup\$ @RobinRyder - Yes! Thanks! Although I'm still far from matching/beating you or qwr... \$\endgroup\$ Jun 8 at 8:20
  • 1
    \$\begingroup\$ I think your current version fails for n=0, unfortunately. \$\endgroup\$ Jun 8 at 8:38
  • 2
    \$\begingroup\$ "if"((n=scan())%%2,,n) works for -1 byte: you can remove the m, and get an Error: argument is missing, with no default. \$\endgroup\$ Jun 8 at 14:27
6
\$\begingroup\$

C (gcc), 28 15 14 bytes

-13 thanks to Jonathan Allan
-1 thanks to Olivier Grégoire

f(a){a/=~a&1;}

Try it online!

How ~a&1 works is explained in this solution.

\$\endgroup\$
4
  • \$\begingroup\$ No need to print it seems (modifying function arguments is acceptable), so save 13 bytes TIO \$\endgroup\$ Jun 5 at 20:05
  • \$\begingroup\$ Why don't you need to return a? The result of the division is in eax which is also used for return value, but isn't there undefined behaviour in this code? \$\endgroup\$
    – Oskar Skog
    Jun 7 at 10:34
  • 2
    \$\begingroup\$ @OskarSkog Undefined behavior is the way of life when golfing C. \$\endgroup\$ Jun 7 at 14:09
  • 1
    \$\begingroup\$ f(a){a/=~a&1;} saves a byte. See my (lengthy) explanations \$\endgroup\$ Jun 9 at 7:14
6
\$\begingroup\$

Factor, 15 bytes

[ 2 / 1 shift ]

Try it online!

Thanks to @umnikos

Factor, 19 bytes

[ dup 1 + 2 mod / ]

Try it online!

Throws a divide by zero error on odd numbers, while returning even numbers.

Explanation:

  • dup Duplicate the input.

    Stack: (e.g.) 2 2

  • 1 + Add one.

    Stack: 2 3

  • 2 mod Modulo two.

    Stack: 2 1

  • / Divide. (Here is where the error happens for odd input.)

    Stack: 2

Here's a slightly longer version that simply asserts the number is not odd:

[ dup odd? f assert= ]
\$\endgroup\$
1
  • \$\begingroup\$ 15 bytes: [ 2 / 1 shift ] \$\endgroup\$
    – umnikos
    Jul 3 at 13:27
5
\$\begingroup\$

JavaScript (Node.js), 10 bytes

n=>n%2?_:n

Try it online!

Not a very hard answer

\$\endgroup\$
5
  • \$\begingroup\$ I was hoping something like n=>[n][n%2] would work and be shorter, but I can't get TIO working right now, and it's not even shorter! \$\endgroup\$
    – Pureferret
    Jun 7 at 15:00
  • \$\begingroup\$ @Pureferret that wouldn't error on odd numbers as it would simply return undefined. \$\endgroup\$
    – user100690
    Jun 7 at 15:02
  • \$\begingroup\$ Hmm, yup makes sense. If I could have run TIO I would have seen that :D \$\endgroup\$
    – Pureferret
    Jun 7 at 15:16
  • \$\begingroup\$ Ah, beat me to it \$\endgroup\$
    – Yelp
    Jun 8 at 1:32
  • \$\begingroup\$ @Yelp anyone with js knowledge could write this. I just happened to answer first, and thanks to FGITW, I have 4 upvotes. \$\endgroup\$
    – user100690
    Jun 8 at 5:16
5
\$\begingroup\$

05AB1E, 3 bytes

Èи¿

Try it online!

or

È×F

Try it online!

È checks if the input is even. Returns 1 for even numbers, 0 for odd numbers.

  • и creates a list of this many copies of the input, and ¿ calculates the gcd of the list and throws an error for empty lists
  • × repeats the input as a string this many times. This results in the input for even inputs and the empty string for odd inputs. F is a for loop which crashes if it gets the empty string as an argument. In the end the stack is empty and the input is implicitly printed. F could be any of E, F, G and ƒ.
\$\endgroup\$
1
  • \$\begingroup\$ That moment when you create a list and basically implement an if-else statement in 3 god damn bytes \$\endgroup\$ Jun 6 at 10:09
5
\$\begingroup\$

AWK, 11 10 bytes

1/($1%2-1)

Try it online!

Thanks to tail spark rabbit ear for helping drop one char...

Divides by zero if the number is odd, otherwise the test is truthy and the default action prints the commandline..

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Worked without heading +, even 0 is given. \$\endgroup\$ Jun 6 at 11:03
  • \$\begingroup\$ Hmmm, I don't get that (meaning 0 printing w/o the +) from the commandline, but it does work on TIO for some reason.. I'll update the code and add a caveat in the description, thanks! \$\endgroup\$
    – cnamejj
    Jun 10 at 18:55
  • \$\begingroup\$ are you a non-GNU AWK user or a non-POSIX AWK user? \$\endgroup\$ Jun 11 at 8:21
  • 1
    \$\begingroup\$ How about -f path/to/your/script? \$\endgroup\$ Jun 11 at 23:32
  • 1
    \$\begingroup\$ Well, I can't find a system that DOES need the leading + so my best guess is that an earlier version of the code needed it? But I took your suggestion and dropped it from the answer. \$\endgroup\$
    – cnamejj
    Jun 12 at 9:29
4
\$\begingroup\$

Jelly, 4 bytes

ḂNXo

Try it online!

Jelly, 5 bytes

%2NXo

Try it online!

Look ma, no unicode!

ḂNXo  Main Link
Ḃ     Same thing as %2. 1 if it's odd, 0 if it's even.
 N    Negate. -1 if it's odd, 0 if it's even.
  X   Random number. Errors with -1 as input, returns 0 with 0 as input.
   o  Logical OR. If the input was odd, the program's already errored. Otherwise, it's 0,
      so logical OR gives the right value, which is the input.

Unfortunately, since dividing by zero isn't actually an error in Jelly, I cannot use that. Although, it wouldn't save me any bytes: %2C:@ is the same length.

\$\endgroup\$
7
  • \$\begingroup\$ Damn this is fascinating, how the hell does this even work \$\endgroup\$ Jun 5 at 18:20
  • \$\begingroup\$ @LeopardLGD Added a full explanation \$\endgroup\$
    – hyper-neutrino
    Jun 5 at 18:21
  • \$\begingroup\$ I am just very surprised how these golfing languages already have prebuilt tools for basically anything. \$\endgroup\$ Jun 5 at 18:26
  • 1
    \$\begingroup\$ @LeopardLGD, that's the whole point of golfing languages! \$\endgroup\$
    – Shaggy
    Jun 5 at 18:39
  • 2
    \$\begingroup\$ @LeopardLGD, that speaks either to the triviality of the challenge or the quality of the golfer or both. \$\endgroup\$
    – Shaggy
    Jun 5 at 19:02
4
\$\begingroup\$

A0A0, 161 bytes

I0A10A6V0
G-1G-1A5G0D2A0
A8O0
G1
A0A0
A0C3G1G1G1G1G1A0
A0L1S2M4
A0A1G-3G-3G-3G-3G-3A0
G-3


G-1G-1



A0A0
C3G1G1A0C3G1G1A0
G-10G1G1A0G-10G1G1A0
A0A1G-3G-3A0
G-3

Since A0A0 does not have a modulo, or division, this uses repeated subtraction by 2 to get down to either a 0 or 1. If 1, the number is odd, if 0 the number is even.

I0  A10 A6 V0
G-1 G-1 A5 G0 D2 A0
A8  O0

Reads a number from the input I0 and distributes the operand over two other lines. A5 G0 D2 A0 completes the loop below in which we inserted the operand and A8 O0 finishes the print function.

A0  A0
A0  C3 G1  G1  G1  G1  G1  A0
A0  L1 S2  M4  V0  G0  D2  A0
A0  A1 G-3 G-3 G-3 G-3 G-3 A0
G-3

With the inserted code executed before this completes a loop that compares the operand to 1 and jumps to 1 (operand is greater than 1), 0 (operand is equal to 1) or -1 (operand is less than one) lines down depending on the comparison. We add 2 to this and multiple it by 4, to get the offsets 12, 8 and 4.

A0   A0
C3   G1 G1  A0  C3   G1 G1 A0
G-10 G1 G1  A0  G-10 G1 G1 A0
A0   A1 G-3 G-3 A0
G-3

This is a loop located 12 lines down, executed when the operand is 2 or more, to jump back up to the repeated subtraction loop. It's padded with no-ops G1, since the loop must have three instructions or more to work.

At offset 8 is nothing, to stop the program.

At offset 4 is the code A6 V0 O0. The A6 is a leftover from copying, but the last two print the initial value that was entered.

Edit: forgot to mention, but A0A0 has no errors or exceptions, so this only halts.

\$\endgroup\$
4
\$\begingroup\$

Zsh (math function), 14 bytes

((1/1&~$1,$1))

Try it online!

Unlike in Bash, C and many other languages, in Zsh & binds more tightly than / by default, allowing us to get division by zero on odd numbers with just 1 / 1 & ~$1.

(Zsh does have a C_PRECEDENCES option which changes arithmetic binding to the traditional order.)

\$\endgroup\$
4
\$\begingroup\$

><>, 7 bytes

:2%?Cn;

The input should be put onto the stack using the -v command-line argument.

Try it even!
Try it odd!


Explanation:

Initially, the stack contains the input number, \$ n \$.

  • : duplicates the top of stack: [\$n\$, \$n\$]
  • 2 pushes \$2\$ onto stack: [\$n\$, \$n\$, \$2\$]
  • % pops two values and pushes their modulo: [\$n\$, \$n \% 2\$]
  • ? pops the top value, and if it is \$0\$, the next instruction is skipped: [\$n\$]

If \$n \% 2 \neq 0\$:

  • C is not a valid instruction, so the program crashes.

If \$n \% 2 = 0\$:

  • n pops off the top value (\$n\$) and prints it: []
  • ; terminates the program.
\$\endgroup\$
3
  • 1
    \$\begingroup\$ You don't need the ; \$\endgroup\$
    – Jo King
    Jun 10 at 8:08
  • \$\begingroup\$ @JoKing Do I not? The question author specified "As for even numbers, no errors must occur and the output is the number." in a comment on the question. \$\endgroup\$
    – Borka223
    Jun 11 at 9:21
  • \$\begingroup\$ Ah, that part wasn't in the actual question so I missed it \$\endgroup\$
    – Jo King
    Jun 13 at 3:28
4
\$\begingroup\$

R, 20 19 bytes

(x=scan())[[!x%%2]]

Try it online!

R 4.1, 15 14 bytes

\(x)x[[!x%%2]]

Takes advantage of the fact that an R numeric is automatically a vector.

-1 byte by using a different indexing error due to Dominic van Essen.

\$\endgroup\$
3
  • \$\begingroup\$ 19 bytes... \$\endgroup\$ Jun 7 at 20:45
  • \$\begingroup\$ (and 14 bytes for the R 4.1 version using the same strategy: \(x)x[[!x%%2]]) \$\endgroup\$ Jun 7 at 20:48
  • \$\begingroup\$ @DominicvanEssen thanks, updated \$\endgroup\$
    – qwr
    Jun 7 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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