24
\$\begingroup\$

Task

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

Example with Python

Input: 1
Output:

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

Another example

Input: 2
Output: 2

Rules

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

LEADERBOARD

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

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

65 Answers 65

4
\$\begingroup\$

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

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

\$\endgroup\$
2
\$\begingroup\$

Racket, 29 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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!

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

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.

enter image description here

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
5
  • 1
    \$\begingroup\$ 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... \$\endgroup\$ Jun 10 at 8:13
  • \$\begingroup\$ Ah I must have been not awake enough when initially making the programs. It is easy to fix \$\endgroup\$ Jun 10 at 9:23
  • 1
    \$\begingroup\$ Delete line 1 to save 3 (?) bytes \$\endgroup\$ Jun 10 at 9:37
  • \$\begingroup\$ 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 \$\endgroup\$ Jun 10 at 9:39
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Jun 10 at 9:41
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Go, 79 bytes

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

Python 3, 31 23 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

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

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!

\$\endgroup\$
9
  • \$\begingroup\$ Why not golf it more? You can remove the ==0 part by swapping the two branches \$\endgroup\$
    – user
    Jun 5 at 18:18
  • \$\begingroup\$ 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 \$\endgroup\$
    – hyper-neutrino
    Jun 5 at 18:19
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 5 at 18:22
  • \$\begingroup\$ Here's a slightly golfed version that doesn't change your original too much. \$\endgroup\$
    – user
    Jun 5 at 18:22
  • \$\begingroup\$ @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. \$\endgroup\$
    – user
    Jun 5 at 18:24
1
\$\begingroup\$

Scala, 12 bytes

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

Try it online!

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

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.

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

Zsh, 16 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Does the downvoter have any feedback to suggest? \$\endgroup\$
    – pxeger
    Jul 5 at 9:40
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 at 1:28
  • \$\begingroup\$ @JoKing How to combine? I'm a beginner, so I don't know how. \$\endgroup\$ Jun 6 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 at 6:13
  • \$\begingroup\$ 45 bytes, building upon @ceilingcat's suggestion \$\endgroup\$ Jun 6 at 19:01
  • \$\begingroup\$ 44 bytes by using a null pointer \$\endgroup\$
    – ErikF
    Jun 8 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 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 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 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 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 at 23:01
  • \$\begingroup\$ @RichardDonovan please clarify what you mean by these comments. \$\endgroup\$
    – smarnav
    Jun 12 at 0:11
1
\$\begingroup\$

Haskell, 12 bytes

f x|even x=x

Try it online!

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

TI-Basic, 9 bytes

Input X
identity(X/2
X

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

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

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

Python 3, 21 bytes

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

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 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 \$\endgroup\$ Jun 24 at 23:19
  • \$\begingroup\$ 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. \$\endgroup\$
    – schotti
    Jun 24 at 23:21
  • \$\begingroup\$ 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 :) \$\endgroup\$ Jun 24 at 23:23
  • \$\begingroup\$ ok, understood! \$\endgroup\$
    – schotti
    Jun 24 at 23:24
1
\$\begingroup\$

///, 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.

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

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

Your Answer

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

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