| Bytes | Lang | Time | Link |
|---|---|---|---|
| 005 | Uiua | 250830T161841Z | phidas |
| 006 | Pip | 210605T224903Z | DLosc |
| 066 | Bespoke | 250125T033547Z | Josiah W |
| 005 | ☾ | 250126T145345Z | Joao-3 |
| 008 | Retina | 250125T235554Z | Unrelate |
| 031 | Tcl | 250123T151150Z | sergiol |
| 029 | Tcl | 250123T151706Z | sergiol |
| 016 | CASIO BASIC CASIO fx9750giii | 250123T134214Z | madeforl |
| 033 | Fortran GFortran | 250122T122527Z | roblogic |
| 011 | YASEPL | 240226T182138Z | madeforl |
| 019 | Swift | 240301T162449Z | macOSist |
| 026 | Lua | 240227T194124Z | Ed The & |
| 003 | Vyxal 3 | 240227T143414Z | pacman25 |
| 005 | Rattle | 210607T142319Z | d01 |
| 006 | K ngn/k | 230127T183717Z | coltim |
| nan | 230127T181428Z | The Thon | |
| 005 | Pyt | 230127T142215Z | Kip the |
| 016 | Arturo | 230127T135113Z | chunes |
| 011 | Redirection | 220517T125641Z | m90 |
| 288 | Minecraft Command Blocks | 220515T182741Z | user1003 |
| 138 | A0A0 | 210605T195109Z | stefvans |
| 029 | Python 3 | 220502T134235Z | Joao-3 |
| 006 | Brachylog | 220426T132330Z | Fatalize |
| 025 | Desmos | 220426T083650Z | Aiden Ch |
| 057 | C | 220502T004307Z | littleb2 |
| 070 | Nim | 220501T154700Z | Qaziquza |
| 031 | PostScript | 220501T142551Z | bartysla |
| 091 | Clarion | 220501T134217Z | DylanG |
| 010 | Exceptionally | 220428T155907Z | DLosc |
| 027 | Ruby | 220426T064955Z | oeuf |
| 015 | Python 3 | 220425T143706Z | Tommo499 |
| 021 | Standard ML Moscow ML | 220423T180857Z | Laikoni |
| 035 | AsciiDots | 220309T151312Z | patchara |
| 009 | Perl 5 | 220119T165844Z | Kjetil S |
| 018 | Python 3 | 220119T162146Z | Alan Bag |
| 132 | KonamiCode | 211203T151039Z | Ginger |
| 006 | TIBasic | 210624T174143Z | MarcMush |
| 103 | Acc!! | 210720T202103Z | DLosc |
| 022 | Python 3 | 210606T034233Z | zoomlogo |
| 079 | Go | 210607T235854Z | Zombo |
| 015 | Factor | 210605T183100Z | chunes |
| 012 | /// | 210625T212703Z | AviFS |
| 021 | Python 3 | 210624T231720Z | schotti |
| 012 | Haskell | 210621T151516Z | lynn |
| 012 | MATLAB/Octave | 210605T213307Z | elementi |
| 010 | AWK | 210605T202736Z | cnamejj |
| 252 | COBOLGNU | 210607T183911Z | smarnav |
| 007 | J Jsoftware.com | 210611T210646Z | Richard |
| 010 | <>^v | 210611T155621Z | astroide |
| nan | Commodore BASIC C64/THEC64 | 210609T150859Z | Shaun Be |
| 009 | GNUAPL | 210606T102059Z | rajashek |
| 044 | Whitespace | 210610T144955Z | Kevin Cr |
| 019 | Clojure | 210609T004806Z | wintermu |
| 003 | MathGolf | 210610T140657Z | Kevin Cr |
| 014 | Excel | 210609T154735Z | Engineer |
| 014 | C gcc | 210605T195821Z | a stone |
| 014 | C# Visual C# Interactive Compiler | 210608T130236Z | LiefdeWe |
| 010 | Java JDK | 210606T094116Z | Olivier |
| 002 | Vyxal | 210606T013213Z | emanresu |
| 012 | Grok | 210608T194458Z | Aaroneou |
| 022 | R | 210605T184301Z | Dominic |
| 019 | R | 210607T150721Z | qwr |
| 018 | Starry | 210608T155703Z | Jay Ryan |
| 005 | Japt | 210605T181314Z | Shaggy |
| 014 | PHP | 210606T161046Z | Dewi Mor |
| 017 | Python 3 | 210608T090601Z | trolley8 |
| 016 | PHP | 210607T234213Z | Matthew |
| 007 | ><> | 210607T224816Z | user5828 |
| 029 | Racket | 210607T183203Z | MLavrent |
| 009 | Perl 5 p | 210607T145231Z | Xcali |
| 020 | R | 210606T215645Z | Robin Ry |
| 019 | PowerShell | 210606T151243Z | GMills |
| 027 | Lua | 210607T132448Z | val - di |
| 051 | Python 3 | 210607T125012Z | Olupo |
| 019 | Python 3 | 210607T123318Z | KinuTheD |
| 012 | Ruby | 210607T121236Z | G B |
| 010 | Wolfram Language Mathematica | 210606T204747Z | Greg Mar |
| 045 | C clang | 210606T010812Z | Stack Ex |
| 014 | Zsh math function | 210606T191050Z | GammaFun |
| 013 | Hexagony | 210606T174207Z | je je |
| 006 | BQN | 210606T121646Z | frasiyav |
| 010 | Coconut | 210606T122157Z | wasif |
| 003 | 05AB1E | 210606T100736Z | ovs |
| 010 | Julia 1.0 | 210606T094510Z | MarcMush |
| 016 | Zsh | 210606T061415Z | pxeger |
| 005 | x86 Machine Code | 210606T034627Z | Cody Gra |
| 007 | APL Dyalog Unicode | 210605T235121Z | Adá |
| 006 | Charcoal | 210605T201657Z | Neil |
| 013 | Wolfram Language Mathematica | 210605T185519Z | ZaMoC |
| 013 | Retina 0.8.2 | 210605T201018Z | Neil |
| 012 | Scala | 210605T200742Z | cubic le |
| 016 | Python 2 | 210605T192642Z | xnor |
| 123 | MMIX | 210605T185513Z | NoLonger |
| 010 | JavaScript Node.js | 210605T183534Z | user1006 |
| 062 | Python 3 | 210605T181605Z | LeopardL |
| 003 | Jelly | 210605T182653Z | caird co |
| 004 | Jelly | 210605T181838Z | hyperneu |
| 017 | Python 2 | 210605T181029Z | wasif |
Pip, 6 bytes
VkX%aa
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
Bespoke, 66 bytes
STUFF I DO HATE
snow on doorstep
social platform X
an odd number N
Errors with Invalid stack argument: 0 if the input is odd.
This works by taking the input mod 2, flipping it (i.e. 0 becomes 1 and vice versa), and calling DO ROT; this is a NOP if the argument is 1 (i.e. the input is even), and this throws an error if the argument is 0 (i.e. the input is odd). Here is the same program in "mnemonic" form:
INPUT N
DO COPY
PUSH BI STACKTOP MODULO
STACKTOP F
DO ROT
OUTPUT N
Retina, 8 bytes
*~`.+
*\
Relies entirely on eval stages which do not exist in 0.8.2. Repeats a single backslash \$n\$ times, then attempts to run that as a Retina sub-program--specifically, a match stage where the entire program is a regex, which either matches \$\frac{n}{2}\$ backslashes for even \$n\$ or is syntactically invalid due to a trailing unescaped backslash for odd \$n\$. The eval ~ is wrapped in a dry run stage * to discard its own output (which is 0, unless the input is 0 in which case it's 2) and produce the verbatim input if it doesn't error, but the same can be achieved by appending a ¶ to turn the eval'd program into a replace stage that does nothing if valid instead.
CASIO BASIC (CASIO fx-9750giii), 16 bytes
?→A
A Rmdr 2⟹₁₀1E
A
NOTE: the E in the code is the ENGINEERING SYMBOL E, because that stuff is supported in casio basic
basically, it does an overflow ("Ma") error if the number is odd.
YASEPL, 11 bytes
=a'=b$a%@!<
explanation:
=a'=b$a%@!< packed
=a' get user input and set it to A
=b$a create variable B and set it to content of A
% B = B mod 2
@ if B is equal to 1, then go to point 1 (point 1 does not exist so it errors if its true)
!< else, print A
Swift, 19 bytes
let f={$0/(1-$0%2)}
If $0 (the implicit closure parameter) is even, $0 % 2 is 0, 1 - 0 is 1, and $0 / 1 is the original value. If $0 is odd, $0 % 2 is 1, 1 - 1 is 0, and $0 / 0 ends up calling assertionFailure(_:file:line:).
Lua, 26 bytes
Main code
print(0==n%2 and n or -m)
TIO Header
-- To read input
n = io.read()
Explanation
We read in our input via io.read() into a variable n.
n = io.read()
we then write a ternary statement inside of the print function to test whether n is even or odd. If n is even, we pass it over to print, otherwise we take the negation of a nil global variable to throw an error.
print (0 == n%2 and n or -m)
Note that ternary statements in Lua come in the form of (condition and true-expr or false-expr).
Vyxal 3, 3 bytes
ḃ[x
If the bit parity is 0, then it just outputs the number. Otherwise it gives a "too many recursions" error
Rattle, 5 bytes
|b%[0
Explanation:
| take input
b add to print buffer
% modulo (mod 2 by default)
[0 the first half of an if statement checking whether the answer is 0
Why this works: If the input is even, the result of % is 0 so the if statement is used. The if statement is empty however so nothing happens (and the print buffer is printed implicitly). If the input is odd, the result of % is not 0, so the interpreter will keep skipping forward looking for a closing ] which is not to be found (the language will try to close the bracket from the if statement if it's not allowed to enter the if statement), resulting in an error.
Old best:
Rattle, 8 7 bytes
|b%[1{]
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.
K (ngn/k), 6 bytes
(2!)0/
Sets up a while-loop, testing if 2! (i.e., mod by 2) returns a truthy value when run on the input/current value. If a truthy value is returned, it then attempts to calculate 0@x, which fails with a 'rank error, as atoms cannot be indexed. If (2!) returns a falsey value on the original input, nothing else is run, and the original value is returned unchanged.
Thunno (older versions only), \$ 4 \log_{256}(96) \approx \$ 3.29 bytes
2%?J
This uses a bug which was fixed in v1.1.1. ATO has v1.2.1 so it will not work there.
Explanation
2%mods the input by 2. An even number will result in0and an odd number will result in1.?is anifstatement. If the top of the stack is truthy (1), run the following code:Jmeans''.joinand expects a list. If it doesn't get a list, it throws an error.- Therefore, if the input was odd, it will throw an error.
- If it was even, it will just pass through and output whatever was input
Screenshots
Pyt, 5 bytes
Đ⁺2%/
The code tries to do \${n\over(n+1)\!\!\!\!\mod\!\! 2}\$, which throws a division-by-zero error when n is odd.
Arturo, 16 bytes
$[n][n/(n+1)%2n]
$[n][ ; a function taking an argument n
n / ; n divided by...
(n + 1) % 2 ; n plus one modulo two (error here if n is odd)
n ; push n
] ; end function, implicit return
Re:direction, 11 bytes
++>>
+
v
<
The input number n is represented in the queue as n >s followed by a v. The loop in the first line removes two >s from the front of the queue (with the +s) and adds them back to the back of the queue (with the >s), exiting once less than two remain.
An odd number goes down from the second + and hits the + below it, which consumes the >s left in the queue, coming back to itself each time, until the queue is empty, at which point it produces an error.
An even number goes down from the first + with n >s in the queue, adds a v to re-create the representation of n, and then hits the <, which is ignored in output and points to itself to end the program.
Minecraft Command Blocks, 288 bytes
The commands in command blocks from left to right:
scoreboard objectives add n dummy
scoreboard players set n n <Input>
scoreboard players operation s n = n n
scoreboard players set 2 n 2
scoreboard players operation n n %= 2 n
execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}}
execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block
e
I didn't count the second command block which sets the input. If it's counted the total is 315 bytes plus the length of the number.
Explanation
scoreboard objectives add n dummy creates a scoreboard objective named n. Scoreboard objectives are a way to store numbers similar to variables. Each objective can have an infinite number of variables associated with it, which are accessed like <name> <objective>. So s n would refer to the variable named s in the objective n. All the variables in this program are in the objective n.
scoreboard players set n n <Input> sets n to the input.
scoreboard players operation s n = n n copies the value of n to s. This is required because scoreboard operations overwrite the original value.
scoreboard players set 2 n 2 sets the value of the variable 2 to 2. This is required because scoreboard operations can only be done with two variables, not a variable and a number.
scoreboard players operation n n %= 2 n modulos n by 2.
execute if score n n matches 0 run tellraw @a {"score":{"name":"s","objective":"n"}} prints the value of s (which was set to n) if n is 0, which indicates the number was even.
execute if score n n matches 1 run setblock ~ ~ ~1 redstone_block sets the block to the right of the command block to a redstone block if n is 1, indicating the number is odd. This triggers the last command block.
e is an invalid command, which throws an error, as seen here.
A0A0, 161 146 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.
Python 3, 29 bytes (full program)
a=int(input())
print(a<<a%-2)
Explanation:
a=int(input()) # usual input line
a%-2 # even numbers map to 0, odd numbers map to -1
a<< # part which triggers error (can't shift negative times)
print( ) # output if no error
Brachylog, 7 6 bytes
./₂ℕ∨ị
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
Desmos, 30 29 28 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.
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.
Nim, 70 bytes
proc f(n:int)=
if n mod 2==1:raise Exception.newException""
echo.n
The first solution that came to mind. Rather run-of-the-mill.
PostScript, 31 bytes
.runstdin dup 2 mod 1 eq{x}if =
Requires ghostscript for .runstdin; raises /undefined in x on odd input.
Clarion, 91 bytes
In Clarion, calling a function that is prototyped to return a parameter, but the body of said function does not explicitly return anything causes a runtime exception. I think I might be cheating slightly by not explicitly halting the program, but the dialog that shows after the exception occurs has a "Continue" or "Exit" button, and if you hit continue it will re-trigger the exception, giving you no choice but to terminate anyway.
The input is given as the first command-line parameter.
It's not particularly short compared to the other incredible answers here, but I like Clarion :)
Program
Map;f,?.
Code
i#=Command(1);If i#%2=0;Stop(i#);Else;x#=f().
f Function
Code
Exceptionally, 10 bytes
GI}n%2=0Pn
Explanation
GI}n%2=0Pn
G Get a line of stdin
I Convert to integer
}n Store a copy of that value in n
%2 Mod 2
=0 Assert equal zero; if it's not, throws an error
Pn Otherwise, print n
If the program reaches Pn successfully, it loops back to the beginning, tries to read another line of input, and dies when there is no line to read.
Python 3, 15 Bytes
print([n][n%2])
Standard ML (Moscow ML), 21 bytes
fun$0=0| $x=2+ $(x-2)
Defines a function $ : int -> int that throws an Out_of_memory exception for odd numbers. Requires the Moscow ML interpreter.
- fun$0=0| $x=2+ $(x-2);
> val $ = fn : int -> int
- $ 4;
> val it = 4 : int
- $ 3;
! Uncaught exception:
! Out_of_memory
Standard ML, 22 bytes
fn x=>x div(1-x mod 2)
Anonymous function that throws a Div exception and works in all implementations.
Just for fun, here are some other exceptions:
Match, 24 bytes
fn x=>(fn 0=>x)(x mod 2)
Bind, 29 bytes
fn$ =>let val 0= $mod 2in$end
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.
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
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
We start with a loop that reads digits into the accumulator until hitting a newline:
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)
Python 3, 31 23 22 bytes
lambda x:x&1and a or x
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
Go, 79 bytes
package main
import."fmt"
func main(){a:=[]int{0}
Scan(&a[0])
print(a[a[0]%2])}
Factor, 15 bytes
[ 2 / 1 shift ]
Thanks to @umnikos
Factor, 19 bytes
[ dup 1 + 2 mod / ]
Throws a divide by zero error on odd numbers, while returning even numbers.
Explanation:
dupDuplicate the input.Stack: (e.g.)
2 21 +Add one.Stack:
2 32 modModulo 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= ]
///, 12 bytes
/??/!!//?/?/
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.
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
1for even numbers (which is input itself) - at index
-1for odd numbers (which is invalid index since indices in MATLAB start at 1)
AWK, 11 10 bytes
1/($1%2-1)
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..
COBOL(GNU), 252 bytes
IDENTIFICATION DIVISION.PROGRAM-ID.A.DATA DIVISION.WORKING-STORAGE SECTION.
01 A PIC 9(2).
01 R PIC 9(2).
01 Q PIC 9(2).
PROCEDURE DIVISION.ACCEPT A.DIVIDE A BY 2 GIVING R REMAINDER Q.IF Q IS EQUAL TO 0
DISPLAY A
ELSE
STOP RUN.
STOP RUN.
Please let me know if I can golf this down even more. Don't have time to explain this now.
J (Jsoftware.com), 7 bytes
f=: 13 : '(2|y){y' NB define function f
f NB. display f 7 bytes
=============> this is the function, it is seven characters
] { ~ 2 | ]
<=============
NB. spaces optional
NB. ..and shown for clarity
f 2 NB. test with even number
2
f 3 NB. odd number throws error
|index error: f
| f 3
NB. 2|y finds n mod 2 => 1 odd or 0 even
NB. { use result as index into input
NB. there is only one input so 1 throws error
<>^v, 10 bytes
2,tT%1=VT;
Explanation
2,tT%1=VT;
2 Push 2 to the stack
, Read number from stdin
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)
Commodore BASIC (C64/THEC64, PET, C128, VIC-20, C16/+4) - 18 14 BASIC bytes used <- invalid entries (now removed) - 25 19 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
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.
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)
MathGolf, 3 bytes
¥┌/
Explanation:
¥ # Modulo-2 the (implicit) input-integer
┌ # Invert the boolean (0 becomes 1 and vice-versa)
/ # Integer-divide the (implicit) input-integer by this
# (which causes division by zero errors)
# (after which the entire stack is output implicitly)
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.
C (gcc), 28 15 14 bytes
-13 thanks to Jonathan Allan
-1 thanks to Olivier Grégoire
f(a){a/=~a&1;}
How ~a&1 works is explained in this solution.
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
Java (JDK), 10 bytes
n->n/=~n&1
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.
Vyxal, 2 bytes
₂ḭ
-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)
Grok, 12 bytes
:Y2%}_
qzp h
Copies the input number, and if n%2 = 0, goes down and to the left, prints, and terminates. If n%2 = 1, then it hits _, which errors, since it is an invalid command.
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)
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.
R, 20 19 bytes
(x=scan())[[!x%%2]]
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.
Starry, 18 bytes
, + + *'.
0, push input
1+ duplicate
7+ push 2
4* modulo
0' jump to label 0 if top is non-zero
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.
Japt, 6 5 bytes
Throws a an overflow error on odd numbers. Still convinced there must be a much shorter way 🤔 TypeError/v would work if JavaScript errored on division by 0.
*v ªß
*v ªß :Implicit input of integer
* :Multiply by
v : Divisible by 2?
ª :Logical OR with
ß :A recursive call
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);
Python 3, 17 bytes
lambda x:[x][x%2]
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, 16 bytes
1/!($argv[1]%2);
Divides 1 by opposite the input mod 2. Throws a division by zero error upon odd numbered inputs.
><>, 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\$]2pushes \$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\$:
Cis not a valid instruction, so the program crashes.
If \$n \% 2 = 0\$:
npops off the top value (\$n\$) and prints it: [];terminates the program.
R, 20 bytes
n=scan();n+(n%%2&&a)
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.
PowerShell, 31 25 14 19 bytes
-6 bytes thanks to @mazzy
param($n)$n/!($n%2)
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!
Lua, 27 bytes
print(...%2<1 and...or o())
Not very creative or tricky. Thanks to JS answer for reminding me about ternary operator.
Python 3, 19 bytes
lambda x:x//(1-x%2)
If the number is even, x%2 is 0 and 1-x%2 is 1, so this evaluates to x//1 which is simply x, since floor dividing by 1 gives the original integer.
However, if it is odd, x%2 is 1, 1-x%2 is 0, and this evaluates to x//0 which raises a ZeroDivisionError.
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.
C (clang), 74 45 bytes
main(i){scanf("%i",&i);printf("%i",i/=~i&1);}
Takes an int for input, then uses an if-else statement to choose if the number is odd or even. If the number's odd, it doesn't output anything, but shows the error anyway. Even numbers display the error, but at least the number is inputted.
Thanks to ceilingcat, with the help of Olivier Grégoire, for golfing 29 bytes.
Zsh (math function), 14 bytes
((1/1&~$1,$1))
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.)
Hexagony, 13 bytes
?#\.@!:.!_@\|
Expanded: (Made using Hexagony Colorer)
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.
BQN, 7 6 bytesSBCS
¯2⥊⍟|⊢
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|¬
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
05AB1E, 3 bytes
Èи¿
or
È×F
È 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.Fis 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.Fcould be any ofE,F,Gandƒ.
Julia 1.0, 11 10 bytes
n->n[~n&1]
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
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.
APL (Dyalog Unicode), 7 bytes (SBCS)
Anonymous tacit prefix function
⊢÷1-2|⊢
⊢ 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)$$
Charcoal, 6 bytes
I§0#Nθ
Try it online! Link is to verbose version of code. Explanation:
I§0#N
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.
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.
Python 2, 16 bytes
lambda n:n<<n%-2
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".
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.
Python 3, 62 bytes
i=int(input())
if i%2==0:
print(i)
else:
raise Exception('')
Python 3, 41 bytes thanks to @hyper-neutrino
i=int(input())
if i%2<1:print(i)
else:1/0
Python 3, 37 bytes thanks to @user
i=int(input())
if i%2:g
else:print(i)
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
Jelly, 4 bytes
ḂNXo
Jelly, 5 bytes
%2NXo
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.
Python 2, 17 bytes
lambda n:n/(~n%2)
thanks to @hyper-neutrino for -4 bytes
Python 3, 24 bytes
lambda n:n%2and 1/0 or n







