# 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

## <>^v, 10 bytes

2,tT%1=VT;

##### Explanation
2,tT%1=VT;

2          Push 2 to the stack
t        Pop stack and store into variable t
T       Push the value of the variable t on the stack
%      Modulo top of the stack by second element of stack
1     Push 1
=    Execute next instruction only if top 2 elements of the stack are equal
V   Access variable V, which is undefined and cannot be set because its setter is a keyword (throws error)
T  Push value of variable t onto stack
; Print top of stack


It tests if the number entered modulo 2 returns 1, if so (odd) it tries to access an undefined variable, so that throws an error and exits. If the modulo result is 0 (even), it pushes the number (stored in a variable), and then prints the top of the stack.

online link (the > is the input prompt, it is not an output of the program)

f x|even x=x


Try it online!

# Brachylog, 7 6 bytes

./₂ℕ∨ị


Try it online!

### Explanation

Raising up an error in Brachylog is surprisingly difficult (outside of transpilation errors obviously): in general in declarative logic programming it is better for predicates to fail ("return" false) rather than to throw errors (which has side-effects). Many things that you would expect to error don’t error, they simply don’t succeed to allow backtracking.

The simplest way to raise an error I thought about is to force computation (i.e. use floating point arithmetic, not constraint integer arithmetic) of something undefined: computing ln(0).

@UnrelatedString found a 1 byte way to error: trying to cast a string to an integer, when the input string is a free variable.

.             Input = Output
/₂           Divide it by 2
ℕ          It must result in a non-negative integer
∨        If all that fails
ị       Try to cast a free variable from string to int


# A0A0, 161146 138 bytes

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

G-1G-1

A0A0
C3G1G1A0C3G1G1A0
G-10A0G-10A0
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  A0
A0  L1 S2  M4  V0 G0 D2 A0
A0  A1 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 A0 G-10 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.

Edit 2: Optimized by 15 bytes. I misunderstood the default loop template I make use of in the code. I was under the impression that the amount of G1 and G-3 instructions on line 2 and 4 of the loop resp. needed to match the amount of instructions inside the loop. This is not the case, you only need two of them (although more also work, as long as each line has an equal amount of them). This change removes these extra instructions.

Edit 3: Optimized by 8 bytes. Because of edit two, it turns out that there's actually no minimum of three instructions in the loop. This allows us to drop four instructions (not two, since the loop at the bottom is partially evaluated), totalling eight bytes. I've also added a link to the language page in the post, since that was not present.

# Rattle, 8 7 bytes

|b%[1\]


Try it online!

# Explanation

|            takes the user's input
b           adds this input to a print buffer
%          checks to see if this value is odd (mod 2 is default)
[1 ]      if the resulting value is 1, the code in this if statement executes
\       this is an unsupported character, so it throws an exception
buffer gets printed implicitly if an error was not thrown


# Note

Technically, this code could be reduced to 6 bytes by removing the ] from the end. However, this is not proper Rattle syntax and will likely throw an error in future versions of the language.

# Go, 79 bytes

package main
import."fmt"
func main(){a:=[]int{0}
Scan(&a[0])
print(a[a[0]%2])}


# Python 3, 3123 22 bytes

lambda x:x&1and a or x


Try it online!

Very simple answer, if the number is odd it just tries to check the value of an undefined variable.

-8 bytes! thanks to @Wasif

-1 byte due to replacing if .. else with and..or

# TI-Basic, 9 6 bytes

sum(dim(identity(Ans/2


Tries to create a Ans/2-size identity matrix, which will fail for odd numbers

It will also fails for big-ish numbers depending on the available RAM

# BQN, 7 6 bytesSBCS

¯2⥊⍟|⊢


Try it here.

How it works:

¯2⥊⍟|⊢
⥊     # reshape (this can be any function that is not dyadically invertible)
⍟    # power modifier (𝔽⍟𝔾 applies 𝔽, 𝔾 number of times)
¯2  |⊢  # input mod ¯2, gives 0 if even, ¯1 if odd.


𝔽⍟0 is just equivalent to the identity function so it returns the input, and 𝔽⍟¯1 calls the inverse of 𝔽 1 time, but since ⥊ can't be inverted it gives an error.

## 7 Byte solution:

⊢⊣·!2|¬


Try it here.

How it works:

⊢⊣·!2|¬
¬  # not (in BQN not(x) is extended to 1-x)
2|   # mod 2
·!     # assert (throws an error if not 1)
⊢⊣       # return the input

• Nice! Gonna add you to the leaderboard a little bit later Jun 6, 2021 at 14:04
• +1, and you can get to 5 bytes by dropping the minus sign and using a function that errors when given two integers, for example ∊. Apr 28 at 21:01

# Racket, 29 bytes

(λ(x)(/ x(modulo(add1 x)2)))


Try it online!

# Starry, 18 bytes

, +       +    *'.

0,    push input
1+    duplicate
7+    push 2
4*    modulo
0.    print top


If the input mod 2 is non-zero (1) it attempts to jump to a label that doesn't exist, so it throws an error. Otherwise it reaches the end and prints the number.

Try it online!

# C# (Visual C# Interactive Compiler), 14 bytes

a=>a%2<1?a:a/0

a=>                 # Function taking a
a%2<1            # Boolean which is true if a is even
?a          # If true return a
:a/0      # If false return a/0 which errors


Try it online!

• Why the downvote, is there something I can change? Jun 9, 2021 at 7:10
• Probably downvoted because it fails for negative odd numbers. (I didn't downvote.) Try your code with -3 as input, for instance. Jun 9, 2021 at 7:21
• The challenge does say non-negative integer though, so maybe something else Jun 9, 2021 at 7:23
• Oh, my bad, you're entirely correct! Jun 9, 2021 at 7:26

# Excel, 14 bytes

=A1/ISEVEN(A1)


Input is in the cell A1. The formula can go anywhere else.

ISEVEN() is a built-in that returns TRUE or FALSE. When you perform a math operation (like dividing), Excel treats TRUE as 1 and FALSE as 0. So odd numbers will try to divide by zero and return an error.

# GNU-APL, 9 bytes

{⍵÷2⊤⍵+1}


The above function divdes the given number n with (n+1) mod 2.

Samples for 2 and 3

      {⍵÷2⊤⍵+1} 2
2
{⍵÷2⊤⍵+1} 3
DOMAIN ERROR
λ1[1]  λ←⍵÷2⊤⍵+1


TIO in ngn/apl.

# Commodore BASIC (C64/THEC64, PET, C128, VIC-20, C16/+4) - 18 14 BASIC bytes used <- invalid entries (now removed) - 2519 17 BASIC bytes

0INPUTN:ONNAND1GOTO1:PRINTN


It takes any numeric input and logically ANDs it with 1; Therefore for every odd number, this is 1 otherwise it is 0. This value is passed to the ON...GOTO command. Where this is zero, it passes through to PRINT N and the program exits gracefully. Where this value is one, it will branch to line 1 which is not there, and therefore it reports an ?UNDEF'D STATEMENT ERROR IN 0.

The old entry did not output any valid number, and so was removed. It was something like this:

0INPUTN:N=NAND1:IFNTHENX

• Does this actually output N (as required by the challenge) when N is even? It looks as if it'll just end without outputting anything... Jun 10, 2021 at 8:13
• Ah I must have been not awake enough when initially making the programs. It is easy to fix Jun 10, 2021 at 9:23
• Delete line 1 to save 3 (?) bytes Jun 10, 2021 at 9:37
• How would I get the error in that instance? Or maybe I would. Let's try. But I think the line number is two bytes, the x is 1, then there's two bytes that point at the next line, and each line ends with two or three more bytes in Commodore BASIC Jun 10, 2021 at 9:39
• Because GOTO line 1 will throw an 'UNDEF'D STATEMENT ERROR IN 0' error (since line 1 doesn't exist). Tested on virtualconsoles.com/online-emulators/c64 Jun 10, 2021 at 9:41

# Python 3, 21 bytes

lambda x:x//((x+1)%2)


Try it online!

• Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Python page for ways you can golf your program. I've edited your post slightly to improve the formatting Jun 24, 2021 at 23:19
• thanks a lot, caird! i would actually have preferred to just comment a slightly longer python solution above but i don't have the reputation needed to do so. Jun 24, 2021 at 23:21
• We generally recommend against posting solutions in comments, as answers don't have the be the shortest they can be, so long as they make an effort at golfing :) Jun 24, 2021 at 23:23
• ok, understood! Jun 24, 2021 at 23:24

# ///, 12 bytes

/??/!!//?/?/


Try it online!

The /// language is Turing complete, yet only has one command: a simple /find/replace/. No special characters except the forward and back slashes. Each /find/replace/ loops until it can no more, before moving onto the next. In ///, the input is appended to the end of the program. The link places the input in the footer.

This program uses unary to represent numbers, taking input with ? and returning output with !.

/??/!!/    Replaces all pairs of '?', with pairs of '!'
/?/?/      Replaces any '?' left with itself, creating an infinite loop


On evens, all questions are replaced with exclamations in the first pattern, and the program terminates with as many exclamations as it had questions. The same number is returned in unary.

On odds, after the first pattern there is one question mark left. This gets replaced with itself ad infinitum until TIO times out after 60 seconds.

There's technically no consensus that this counts as an error, but I'm counting TIO as the implementation here. Otherwise, I can certainly write another implementation that times out, or that uses recursion to eventually stack overflow.

# Acc!!, 103 bytes

N
Count i while _%60/48 {
_*60+N
Count j while 10/(_%60)*(i-j+1) {
Write _/60^(i-j+1)%60/(1-_/60%2)
}
}


Dies with a division-by-zero error if the input is odd. Try it online!

### Explanation

N
Count i while _%60/48 {
_*60+N
}


At the end of this loop, the accumulator can be read as a base-60 number whose digits are the entered characters' ASCII codes (the last one being 10 for newline). The loop variable i is one less than the number of digits in the input number. We need to know the length of the number to output the digits in order; since i goes out of scope as soon as its loop exits, we'll need to nest the output loop inside the input loop.

Naively, we could output the digits like so:

Count j while i-j+1 {
Write _/60^(i-j+1)%60
}


But we only want this loop to activate when we've just read a newline; so we multiply the condition by 10/(_%60), which is 1 when the last character read has a code of 10 (or below) and 0 when it has a code above 10:

Count j while 10/(_%60)*(i-j+1) {


Finally, we need an error when the input number is odd. This is the case if the final digit's character code (_/60%60) is odd; 1-_/60%2 will give 0 for odd and 1 for even. Then we can simply divide the output expression by this quantity to get the desired error/no-op behaviors:

Write _/60^(i-j+1)%60/(1-_/60%2)


# KonamiCode, 132 bytes

>>>>(^^)v(>)>(^)v(>)L(>)>(^)v((>))>(^^)S(^)A(^^)v(^)A(^>^)L(^^)v(>)B(^^^)L(^^^)L(^>^)>(>)S((^))>(^)B(>)>(^^)S(>)A(^>)>(^>)<<L(^>)<<<

This is basically identical to my answer here, but with a bit of code on the end that causes an InvalidMemoryIndexError if the number is odd.

$_%2&&die  Try it online! # AsciiDots,41 35 bytes .&#$--\
*#1-*[-]/2#*.
\#?{+}*{%}[/]


Try it online!

# Python 3, 15 Bytes

print([n][n%2])

• Welcome to Code Golf, and nice first answer! Unfortunately, taking input from a predefined variable (here n) is not one of our allowed I/O methods. You'll have to change your submission to a full program or a function like lambda n:[n][n%2] Apr 25 at 14:39

# C, 57 bytes

main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?0/0:c);}


Exploits the ternary conditional to divide by zero (fastest way of causing an error?) if the first argument isn't even. Also abuses the argc variable to store the number.

Note: To compile using LLVM Clang, use flag -std=c89. However, Clang-compiled versions won't just go though with attempting to divide by zero. Sad.

A longer one (works with gcc and clang):

main(c,v)char**v;{c=atoi(1[v]);printf("%d",(c%2)?v[9999]:c);}


Attempts to access memory outside the program's bounds when given an odd number. Try removing some 9s at the cost of making the likelihood of accessing memory outside the program's bounds smaller. Works with three 9s in TIO.

Yes, I know that atoi isn't exactly good, but it's nice and short.

# Desmos, 302928 25 bytes

f(n)=[1...mod(n,2)8!][1]n


A lot of stuff that I tried just gives undefined instead of erroring out, but I finally found something that worked.

Try It On Desmos!

Try It On Desmos! - Prettified

# Python 3, 62 bytes

i=int(input())
if i%2==0:
print(i)
else:
raise Exception('')


Try it online!

# Python 3, 41 bytes thanks to @hyper-neutrino

i=int(input())
if i%2<1:print(i)
else:1/0


Try it online 2!

# Python 3, 37 bytes thanks to @user

i=int(input())
if i%2:g
else:print(i)


Try it online 3!

• Why not golf it more? You can remove the ==0 part by swapping the two branches
– user
Jun 5, 2021 at 18:18
• You can remove some spaces (by inlining your if/else) for a trivial golf. Also, i%2==0 is the same as i%2<1. Also, you can raise 0 which isn't valid but... you're trying to produce an error anyway :) you can also just divide by zero to get an error; that should be the shortest way to obtain any error Jun 5, 2021 at 18:19
• That's true, gonna add it. And to @user, I am not interested much in making these, I am more interested in making the task itself, not the answer. I am doing this just for fun so even if I golf the answer, it won't be a competitive one. Jun 5, 2021 at 18:22
• Here's a slightly golfed version that doesn't change your original too much.
– user
Jun 5, 2021 at 18:22
• @LeopardLGD It doesn't have to be a competitive one - you can just try your best instead of trying to win. It's up to you to decide what to do with your answers, though.
– user
Jun 5, 2021 at 18:24

# Scala, 12 bytes

i=>i/(i+1&1)


Try it online!

# Charcoal, 6 bytes

Ｉ§0#Ｎθ


Try it online! Link is to verbose version of code. Explanation:

Ｉ§0#Ｎ


Cyclically (i.e. modulo 2) index into the string 0# using the input as an integer, and try to cast that character into an integer. This throws a ValueError for #.

θ


Print the input.

# Pip, 6 bytes

VkX%aa


Try it here! Or, here's the 7-byte equivalent in Pip Classic: Try it online!

### Explanation

    a   Command-line argument
%    Mod 2: 0 if even, 1 if odd
kX     Repeat the string ", " that many times
V       Eval
If even, eval empty string (no-op); if odd, eval ", " (parse error)
a  If there wasn't an error, autoprint the command-line argument


# Zsh, 16 bytes

<<<$1>0 <$[\$1%2]


Try it online!

• Does the downvoter have any feedback to suggest? Jul 5, 2021 at 9:40

# Julia 1.0, 11 10 bytes

n->n[~n&1]


Try it online!

Numbers can be indexed by one (4[1] == 4) but any other number will throw an error (0 here when n is odd)

-1 byte thanks to Olivier Grégoire's answer