34
\$\begingroup\$

Task

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

Example with Python

Input: 1
Output:

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

Another example

Input: 2
Output: 2

Rules

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

LEADERBOARD

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

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

90 Answers 90

1 2
3
1
\$\begingroup\$

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

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

Coconut, 10 bytes

n->n<<n%-2

Try it online!

Coconut port of @xnor's trick

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

C (clang), 74 45 bytes

main(i){scanf("%i",&i);printf("%i",i/=~i&1);}

Try it online!

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.

\$\endgroup\$
5
  • \$\begingroup\$ You can flip the if statement pretty easy, as well as remove the printf statement for the error. Try it online!. You can also combine the two sides of the if into one statment for 46 bytes \$\endgroup\$
    – Jo King
    Jun 6, 2021 at 1:28
  • \$\begingroup\$ @JoKing How to combine? I'm a beginner, so I don't know how. \$\endgroup\$ Jun 6, 2021 at 2:12
  • \$\begingroup\$ Dividing i by zero within the print statement if i%2 is 1, otherwise dividing by 1. \$\endgroup\$
    – Jo King
    Jun 6, 2021 at 6:13
  • \$\begingroup\$ 45 bytes, building upon @ceilingcat's suggestion \$\endgroup\$ Jun 6, 2021 at 19:01
  • 1
    \$\begingroup\$ 44 bytes by using a null pointer \$\endgroup\$
    – ErikF
    Jun 8, 2021 at 12:56
1
\$\begingroup\$

Lua, 27 bytes

print(...%2<1 and...or o())

Try it online!

Not very creative or tricky. Thanks to JS answer for reminding me about ternary operator.

\$\endgroup\$
1
  • \$\begingroup\$ Trying to take the negative of nil throws an error, so ...or-o saves 2 bytes over ...or o() \$\endgroup\$
    – ovs
    Jun 10, 2021 at 13:49
1
\$\begingroup\$

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.

Try it online!

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

Grok, 12 bytes

:Y2%}_
qzp h

Try it Online!

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.

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

MathGolf, 3 bytes

¥┌/

Try it online.

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)
\$\endgroup\$
1
\$\begingroup\$

Clojure,20 19 bytes

#(/ %(- 1(mod % 2)))

#(/ %(mod(inc %)2))

Try it online!

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

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
\$\endgroup\$
1
\$\begingroup\$

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.

https://tio.run/##bY4xbwIxDIX3@xUey5AI2DqaxEQWR5JzclSMLQIWBFKrSv31Tc3SY8DT82f5vXe4fdwu5nz9bo09xcprdlg5RfC846LCZklBcGvYW7QeK06ntyQbjsGUmgQDQSF3/7Ud3Ge@AITMDl5flrOJyRM2PDDNc@RHoSkHnaNcQeOVeFLb1R6WEHSLQQ2FtsjRk8Bgea1uXICGEXuoCead55J73AN21BfqtG0GGbXmv2rt93C6vJ@/mvlp5vR5PP4B

\$\endgroup\$
5
  • \$\begingroup\$ I am not familiar with this language, but can't you write that all in a single line instead of several lines? \$\endgroup\$ Jun 8, 2021 at 15:41
  • 1
    \$\begingroup\$ at least, on the GNU COBOL compiler, they have to be on differing lines, otherwise I get errors. \$\endgroup\$
    – smarnav
    Jun 8, 2021 at 15:59
  • \$\begingroup\$ * GET REMAINDER AFTER DIV BY 2 INTO R * MUTIPLY R BY 10000 INTO C * (IF NO REMAINDER, C IS NOW 0, * IF REMAINDER, C IS 10000) * AFTER ADDING 1, C IS 1 IF INPUT IS EVEN * AND 10001 IF INPUT IS ODD * USING C AS A SUBSCRIPT, ONLY C=1 IS LEGIT. * MOVING 1 INTO THE 10001ST OCCURENCE OF N * CAUSES THIS SYSTEM ERROR---> * attempt to reference unallocated memory *(signal SIGSEGV) ETC. * MOVING 1 INTO 1ST * OCCURENCE IS FINE, AND PROGRAM CONTINUES \$\endgroup\$ Jun 11, 2021 at 22:59
  • \$\begingroup\$ ID DIVISION. PROGRAM-ID.A. DATA DIVISION. WORKING-STORAGE SECTION. 1 A PIC 99. 1 R PIC 9. 1 N PIC 9 OCCURS 1. 1 C PIC 9(6). PROCEDURE DIVISION. ACCEPT A. DIVIDE A BY 2 GIVING R REMAINDER R. MULTIPLY 10000 BY R GIVING C. ADD 1 TO C. MOVE 1 TO N (C). DISPLAY A. \$\endgroup\$ Jun 11, 2021 at 23:01
  • \$\begingroup\$ @RichardDonovan please clarify what you mean by these comments. \$\endgroup\$
    – smarnav
    Jun 12, 2021 at 0:11
1
\$\begingroup\$

Python 3, 18 bytes

lambda n:n/(n%2<1)

Try it online!

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

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)

Try it online!

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)

Try it online!

Bind, 29 bytes

fn$ =>let val 0= $mod 2in$end

Try it online!

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

Ruby, 27 bytes

n=gets.to_i;p(n%2==0?n:n/0)

Attempt This Online!

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

Exceptionally, 10 bytes

GI}n%2=0Pn

Attempt This Online!

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.

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

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ This is why the score is 29: Both lines are 14 bytes long, with the newline it's 29 \$\endgroup\$
    – Joao-3
    May 3, 2022 at 13:46
1
\$\begingroup\$

Re:direction, 11 bytes

++>>
 +
v
<

Try it online!

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.

Diagram of execution paths

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

Pyt, 5 bytes

Đ⁺2%/

Try it online!

The code tries to do \${n\over(n+1)\!\!\!\!\mod\!\! 2}\$, which throws a division-by-zero error when n is odd.

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

K (ngn/k), 6 bytes

(2!)0/

Try it online!

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.

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

Ruby, 12 bytes

->n{n/=1&~n}

Try it online!

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ Do you need the //? It seems like only integers are passed, so you can use / instead \$\endgroup\$
    – user100690
    Jun 7, 2021 at 13:06
  • \$\begingroup\$ @ophact The // is necessary to convert it back to an integer, since in Python 3, / always returns a float. x // y is effectively int(x/y). Good question! \$\endgroup\$ Jun 7, 2021 at 13:37
0
\$\begingroup\$

Python 3, 51 bytes

i=input()
if int(i)&1:raise Exception
else:print(i)

Try it online

\$\endgroup\$
1
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

PostScript, 31 bytes

.runstdin dup 2 mod 1 eq{x}if =

Requires ghostscript for .runstdin; raises /undefined in x on odd input.

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

Nim, 70 bytes

proc f(n:int)=
  if n mod 2==1:raise Exception.newException""
  echo.n

Attempt This Online!

The first solution that came to mind. Rather run-of-the-mill.

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

Arturo, 16 bytes

$[n][n/(n+1)%2n]

Try it

$[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
\$\endgroup\$
0
\$\begingroup\$

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 in 0 and an odd number will result in 1.
  • ? is an if statement. If the top of the stack is truthy (1), run the following code:
    • J means ''.join and 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

Screenshot 1

Screenshot 2

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

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
\$\endgroup\$
0
\$\begingroup\$

Vyxal 3, 3 bytes

ḃ[x

Try it Online!

If the bit parity is 0, then it just outputs the number. Otherwise it gives a "too many recursions" error

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

Lua, 26 bytes

Main code

print(0==n%2 and n or -m)

Try it online!

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

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

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:).

\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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