# iHateOddNumbers

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.

<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.rawh\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> 

• I would highly recommend you start posting your challenge ideas to the Sandbox first to get feedback Jun 5, 2021 at 19:32
• related Jun 6, 2021 at 0:36
• 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.
– user
Jun 6, 2021 at 16:36
• 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.
– user
Jun 6, 2021 at 21:05
• 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 :) Jun 7, 2021 at 2:10

# 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".

# 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

# Hexagony, 13 bytes

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


Try it online!

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:

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.

• Hand-drawn Hexagony execution map is a great evolution path from hand-drawn circles Jun 7, 2021 at 13:10

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

• 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". Jun 6, 2021 at 4:31
• 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. Jun 6, 2021 at 6:58
• oh my god what the is going on here Jun 6, 2021 at 8:20
• 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 Jun 6, 2021 at 10:34
• @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. Jun 8, 2021 at 8:47

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

# MATLAB/Octave, 1713 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)

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

• 10 bytes
– att
Jun 7, 2021 at 5:51
• So clever! Thank you Jun 7, 2021 at 6:15

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

• 2 bytes Jun 8, 2021 at 19:40
• YOO 2 BYTES WHAT THE HELL Jun 13, 2021 at 10:08
• @LeopardLGD It's because Vyxal has no booleans, only 0 and 1. Jun 13, 2021 at 10:09
• I see the explanation, I am just very glad and surprised for someone to finally break the 3 bytes barrier Jun 13, 2021 at 10:09
• @LeopardLGD Vyxal's cool like that. Jun 13, 2021 at 10:10

# PowerShell, 312514 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! • @mazzy Beautiful, can't believe I missed this. Jun 6, 2021 at 17:28 • -1 byte more Jun 6, 2021 at 17:29 • I'm sorry. The code 1/... does not output that number. It should be "$args"/... or param($n)$n/... Jun 6, 2021 at 17:30
• Doesn't currently conform to spec since even numbers aren't printed. Jun 7, 2021 at 13:20
• @valisstillwithMonica fixed. Jun 7, 2021 at 13:42

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

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

# 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!

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

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. # 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. # 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);  • This was mine: $i/=1-$i%2; Jun 6, 2021 at 23:39 • @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. Jun 7, 2021 at 0:48
• 1/!($argv[1]%2); There you go Jun 7, 2021 at 23:36 • @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. Jun 8, 2021 at 14:48 • ${$argv[1&$argv[1]+1]/1}; 25 bytes, no echos Jun 22, 2021 at 0:08

# 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= ]

• 15 bytes: [ 2 / 1 shift ] Jul 3, 2021 at 13:27

# JavaScript (Node.js), 10 bytes

n=>n%2?_:n


Try it online!

• 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! Jun 7, 2021 at 15:00
• @Pureferret that wouldn't error on odd numbers as it would simply return undefined.
– user100690
Jun 7, 2021 at 15:02
• Hmm, yup makes sense. If I could have run TIO I would have seen that :D Jun 7, 2021 at 15:16
• Ah, beat me to it
– Yelp
Jun 8, 2021 at 1:32
• @Yelp anyone with js knowledge could write this. I just happened to answer first, and thanks to FGITW, I have 4 upvotes.
– user100690
Jun 8, 2021 at 5:16

# 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. # Wolfram Language (Mathematica), 13 bytes #/Mod[#+1,2]&  Try it online! -1 byte from @att • 13 bytes – att Jun 5, 2021 at 20:09 • #+0^(-1)^#& works for 11 bytes (and also is a new mechanism among the answers, as far as I can tell) Jun 6, 2021 at 18:50 • @GregMartin very nice! I think that you should post this as your own answer... I want to upvote it! Jun 6, 2021 at 20:34 • Cool, answer posted :) Jun 6, 2021 at 20:48 # 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)$$ # Perl 5-p, 9 bytes $_%2&&die


Try it online!

• $[=$_%2 for 7 Jun 8, 2021 at 0:54

# 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

• Wow, that's indeed short Jun 5, 2021 at 18:15
• @LeopardLGD, give it a minute and one of the other golfing languages will be along to kick my ass! Jun 5, 2021 at 18:18
• Your prediction was indeed correct :) Jun 5, 2021 at 18:18
• Oh no. RIP to this! Jun 5, 2021 at 18:20
• Not even a minute, @hyper-neutrino 😂 Jun 5, 2021 at 18:21

# R, 2523 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.

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

# C (gcc), 2815 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.

• No need to print it seems (modifying function arguments is acceptable), so save 13 bytes TIO Jun 5, 2021 at 20:05
• 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? Jun 7, 2021 at 10:34
• @OskarSkog Undefined behavior is the way of life when golfing C. Jun 7, 2021 at 14:09
• f(a){a/=~a&1;} saves a byte. See my (lengthy) explanations Jun 9, 2021 at 7:14

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.. • Worked without heading +, even 0 is given. – user100411 Jun 6, 2021 at 11:03 • 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! Jun 10, 2021 at 18:55 • are you a non-GNU AWK user or a non-POSIX AWK user? – user100411 Jun 11, 2021 at 8:21 • How about -f path/to/your/script? – user100411 Jun 11, 2021 at 23:32 • 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. Jun 12, 2021 at 9:29 # 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 ƒ. • That moment when you create a list and basically implement an if-else statement in 3 god damn bytes Jun 6, 2021 at 10:09 # 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. • Damn this is fascinating, how the hell does this even work Jun 5, 2021 at 18:20 • @LeopardLGD Added a full explanation Jun 5, 2021 at 18:21 • I am just very surprised how these golfing languages already have prebuilt tools for basically anything. Jun 5, 2021 at 18:26 • @LeopardLGD, that's the whole point of golfing languages! Jun 5, 2021 at 18:39 • @LeopardLGD, that speaks either to the triviality of the challenge or the quality of the golfer or both. Jun 5, 2021 at 19:02 # 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.)

# ><>, 7 bytes

:2%?Cn;


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

### 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.
• You don't need the ;
– Jo King
Jun 10, 2021 at 8:08
• @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. Jun 11, 2021 at 9:21
• Ah, that part wasn't in the actual question so I missed it
– Jo King
Jun 13, 2021 at 3:28

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

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

# Whitespace, 44 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S S S T S N
_Push_2][T  S T T   _Modulo][N
T   S N
_If_0_Jump_to_Label_EVEN][N
S N
S N
_Jump_to_nonexistent_Label][N
S S N
_Create_Label_Even][T   N
S T _Print_as_integer]


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

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer input = STDIN as integer
Integer temp = input modulo-2
If (temp == 0):
Go to label EVEN
Go to nonexistent label (causing an error)

Label EVEN:
Print input as integer
(also shows an error: no exit defined; could be prevented by adding three trailing newlines)
`