[Question]
      [
Since Halloween is coming up I thought I might start a fun little code golf challenge!
The challenge is quite simple. You have to write a program that outputs either `trick` or `treat`.
"The twist?" you may ask. Well let me explain:
Your program has to do the following:
* Be compilable/runnable in two different languages. Different versions of the same language don't count.
* When you run the program in one language it should output `trick` and the other should output `treat`. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins.
A few explanations:
**Valid outputs** (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):
```
"trick"
"Treat"
"    TReAt"
"
     tRICk          "
```
**Invalid outputs**:
```
"tri ck"
"tr
eat"
"trck"
```
I'm interested to see what you can come up with! Happy Golfing!
I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=97472,OVERRIDE_USER=23417;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=o.replace(TAGS_REG,"")),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i,TAGS_REG = /(<([^>]+)>)/ig;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

[Answer]
## Python / Windows Batch, 25 bytes
```
print"trick"#||echo.treat
```
Everything after the # is interpreted as a comment by python, while the || is an OR in batch, saying that as the previous command failed, execute this one.
I also like the use of an OR as it almost reads "trick or treat" :)
[Answer]
# Whitespace / Starry, 135 bytes
Here's to a clear night sky on Halloween!
```
  + +    +      + +
    +
* +   +*      +     *
   +    *
     + +
 +* +
 +* + .  + .   +      +* +   +* . . .
```
*Note that whitespace on empty lines may not be preserved if you copy from the above code*
Whitespace outputs "TRICK". [Try it Online!](http://whitespace.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)

Starry outputs "TREAT". [Try it Online!](http://starry.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)
## Explanation
### Starry
Starry ignores all tabs and new lines so the code it reads is the following
```
         + + + + + +  * +   +*   +  *   +  *       + +   +* +   +* + .  + .   +      +* +   +* . . .
```
Bytewise, pushing values is very expensive compared to stack and arithmetic operations in Starry. The code starts by pushing and duplicating 4 and the performs a number of operations on it and with 2 and 1 pushed later on produces all of the required ASCII values.
**Annotated Code**
```
Stack (after op)    Code        Operation
4                            +  Push 4
4 4 4 4 4 4          + + + + +  Duplicate top of stack 5 times
4 4 4 4 16            *         Multiply top two items
4 4 4 4 16 16        +          Duplicate top of stack
4 4 4 16 4 16          +        Rotate top three items on stack right
4 4 4 16 20         *           Add top two items
4 4 20 4 16            +        Rotate...
4 4 20 64             *         Multiply...
4 64 4 20              +        Rotate...
4 64 80               *         Multiply...
4 64 80 2                  +    Push 2
4 64 80 2 2          +          Duplicate...
4 64 2 80 2            +        Rotate...
4 64 2 82           *           Add...
4 64 2 82 82         +          Duplicate...
4 64 82 2 82           +        Rotate...
4 64 82 84          *           Add...
4 64 82 84 84          +        Rotate...
4 64 82 84           .          Pop and print as character (T)
4 64 84 82            +         Swap top two items on stack
4 64 84              .          Pop and print... (R)
84 4 64                +        Rotate...
84 4 64 1                 +     Push 1
84 4 65             *           Add...
84 4 65 65           +          Duplicate...
84 65 4 65             +        Rotate...
84 65 69            *           Add...
84 65                .          Pop and print... (E)
84                   .          Pop and print... (A)
                     .          Pop and print... (T)
```
### Whitespace
As the name may suggest, Whitespace only parses the three whitespace characters—space, tab, and newline. Unlike the Starry, the Whitespace simply pushes the ASCII values of `T`, `R`, `I`, `C`, and `K` and the prints them.
**Annotated Code**
```
<Space><Space><Space><Tab><Space><Tab><Space><Space><Tab><Space><LF> Push the ASCII value of R
<Space><Space><Space><Tab><Space><Tab><Space><Tab><Space><Space><LF> Push the ASCII value of T
<Tab><LF><Space><Space> Pop and print the T
<Tab><LF><Space><Space> Pop and print the R
<Space><Space><Space><Tab><Space><Space><Tab><Space><Space><Tab><LF> Push the ASCII value of I
<Tab><LF><Space><Space> Pop and print the I
<Space><Space><Space><Tab><Space><Space><Tab><Space><Tab><Tab><LF>   Push the ASCII value of K
<Space><Space><Space><Tab><Space><Space><Space><Space><Tab><Tab><LF> Push the ASCII value of C
<Tab><LF><Space><Space> Pop and print the C
<Tab><LF><Space><Space> Pop and print the K
<LF><LF><LF>            Terminate the program. The following line is not run.
<Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><LF>
```
The interweaving of pushes and prints was chosen based solely on aesthetic reasons as it does not affect the byte count.
[Answer]
# [2sable](http://github.com/Adriandmen/2sable) / [pl](https://github.com/quartata/pl-lang), 8 bytes
```
0000000: 74 72 65 61 74 93 d0 cb                          treat...
```
Both programs have been tested locally with the same 8 byte file, so this is a proper polyglot.
### 2sable: trick
This is the program in [code page 1252](https://en.wikipedia.org/wiki/Windows-1252#Code_page_layout).
```
treat“ÐË
```
[Try it online!](http://2sable.tryitonline.net/#code=dHJlYXTigJzDkMOL&input=)
### pl: treat
This is the program in [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).
```
treatô╨╦
```
[Try it online!](http://pl.tryitonline.net/#code=dHJlYXTDtOKVqOKVpg&input=)
## How it works
### 2sable: trick
```
t         Square root. Errors since there is no input. The exception is caught, the
          stack left unaltered, and the interpreter pretends nothing happened.
 r        Reverse stack.
          Reversed empty stack is still empty stack. ;(
  e       Compute nCr. Errors since there is no input.
   a      Alphanumeric test. Errors since there is no input.
    t     Square root. Errors since there is no input.
     “    Begin a lowercase string literal.
      Ð     Excluding ‘, ’, “, and ”, Ð is the 71st non-ASCII character in CP1252.
       Ë    Excluding ‘, ’, “, and ”, Ë is the 66th non-ASCII character in CP1252.
          (implicit) End string literal.
          Both characters together fetch the dictionary word at index
          71 * 100 + 66 = 7166, which is 'trick'.
```
### pl: treat
```
treat     Bareword; push the string "treat" on the stack.
     ô    Unimplemented. Does nothing.
      ╨   Flatten the stack. This doesn't affect the output.
       ╦  Unimplemented. Does nothing.
```
[Answer]
# Linux ELF x86 / DOS .COM file, 73 bytes
```
00000000  7f 45 4c 46 01 00 00 00  1a 00 00 00 1a 00 43 05  |.ELF..........C.|
00000010  02 00 03 00 1a 00 43 05  1a 00 43 05 04 00 00 00  |......C...C.....|
00000020  eb 0c b4 09 ba 41 01 cd  21 c3 20 00 01 00 b2 05  |.....A..!. .....|
00000030  b9 3b 00 43 05 cd 80 2c  04 cd 80 74 72 69 63 6b  |.;.C...,...trick|
00000040  00 74 72 65 61 74 24 eb  d9                       |.treat$..|
00000049
```
NASM source:
```
ORG 0x05430000
BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class 32b   | -- | type: PT_LOAD      |
                                                ; |*data none   |    |                    |
                                                ; |*version 0   |    |                    |
                                                ; |*ABI SysV    |    |                    |
DD 0x01a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  DD 0x0543001a                           ; |*PADx7       | -- | vaddr = 0x0543001a |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x0543001a                                   ; |*version     | -- | filesz             |
;       inc     ebx     ; STDOUT_FILENO         ; |             |    |                    |
;       mov     eax, 4  ; SYS_WRITE             ; |             |    |                    |
DD 0x0543001a                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
        jmp     short skip                      ; |*sh offset   | -- |*align              |
BITS 16                                         ; |             |    |                    |
treat:  mov     ah, 9                           ; |             | -- |                    |
        mov     dx, trick + 0x100 + 6           ; |*flags ______|    |                    |
        int     0x21                            ; |______/      |    +--------------------+
        ret                                     ; |*ehsize      |
BITS 32                                         ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
skip:                                           ; |             |
        mov     dl, 5   ; strlen("trick")       ; |*shentsize   |
        mov     ecx, trick                      ; |*shnum       |
                                                ; |*shstrndx    |
                                                ; +-------------+
        int     0x80
        sub     al, 4   ; SYS_EXIT
        int     0x80
trick:  DB      "trick/treat$"
BITS 16
        jmp     short treat
```
This uses the fact that the ELF header starts with 7F 45, which, interpreted as x86 code, is a jump.
The relevant parts for the DOS .COM:
```
-u100 l2
07D2:0100 7F45          JG      0147
-u147 l2
07D2:0147 EBD9          JMP     0122
-u122 l8
07D2:0122 B409          MOV     AH,09
07D2:0124 BA4101        MOV     DX,0141
07D2:0127 CD21          INT     21
07D2:0129 C3            RET
-d141 l6
07D2:0140     74 72 65 61 74 24   -                           treat$
```
[Answer]
# [evil](http://esolangs.org/wiki/Evil) / [ZOMBIE](http://www.dangermouse.net/esoteric/zombie.html), 109 bytes
Another spooky answer !
```
xf is a vampire summon task f say "trick" stumble say "jzuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw" animate bind
```
The `ZOMBIE` code defines a `vampire` named `xf` whose only task `f` is activated at instanciation and will output `trick` once before being deactivated by `stumble`. The other `say` call is dead code (how appropriate !) for `ZOMBIE`, but contains most of the `evil` code.
For `evil`, the `xf` name is a call to jump to the next `j`, which precedes the `zuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw` zombie moan that crafts and output `treat`. The code following is either executed (lowercase letters) or ignored but since there's no `w` no output should be produced.
[Answer]
## Python / Perl, 28 bytes
```
print([]and"trick"or"treat")
```
## Explanation
Since `[]` is an ArrayRef in Perl, it's truthy, but it's an empty array in Python, therefore falsy.
[Answer]
## PHP / JavaScript, ~~32~~ 30 bytes
Displays `trick` in PHP and `treat` in JS.
```
NaN?die(trick):alert('treat');
```
The unknown `NaN` constant is implicitly converted to a string by PHP, making it truthy. It's falsy in JS.
### Alternative method, 38 bytes
```
(1?0:1?0:1)?die(trick):alert('treat');
```
The ternary operator is right-associative in JS:
```
                1 ? 0 : 1 ? 0 : 1
 is parsed as:  1 ? 0 : (1 ? 0 : 1)
 which equals:  0
```
And left-associative in PHP:
```
                1 ? 0 : 1 ? 0 : 1
 is parsed as:  (1 ? 0 : 1) ? 0 : 1
 which equals:  1
```
[Answer]
# HTML / HTML+JavaScript, 53 bytes
```
treat<script>document.body.innerHTML='trick'</script>
```
`treat` is the document´s text content in HTML.
If JS is enabled, it will replace the HTML content with `trick`.
[Answer]
# C / Java 7, ~~165~~ ~~155~~ ~~128~~ ~~123~~ ~~122~~ ~~120~~ 103 bytes
```
//\
class a{public static void main(String[] s){System.out.print("treat"/*
main(){{puts("trick"/**/);}}
```
//\ makes the next line also a comment in C but is a regular one line comment in Java, so you can make C ignore code meant for Java and by adding /\* in the second line you can make a comment for Java that is parsed as code by C.
Edit:
I improved it a little bit by reorganizing the lines and comments.
Edit2:
I did some more reorganizing and shortened it even more.
Edit3:
I added corrections suggested by BrainStone to remove 5 bytes, thanks :)
Edit4:
One newline turned out to be unnecessary so I removed it.
Edit5:
I changed printf to puts.
Edit6:
I added a correction suggested by Ray Hamel.
[Answer]
# Jolf + Chaîne, 12 bytes
Because Chaîne cannot accept a file to upload with an encoding, I assume UTF-8. (If I could assume ISO-8859-7, this would be 11 bytes, but that would be unfair.)
```
trick«treat
```
In Chaîne, `«` begins a comment, and the rest is printed verbatim. In Jolf, `«` begins a string. Thankfully, `trick` does nothing harmful (`10; range(input, parseInt(input))` basically), and `treat` is printed.
[Try Jolf here!](http://conorobrien-foxx.github.io/Jolf/#code=dHJpY2vCq3RyZWF0)
[Try Chaîne here!](http://conorobrien-foxx.github.io/Cha-ne/?code%3Dtrick%C2%ABtreat%7C%7Cinput%3D)
They both work on my browser (firefox, latest version), but the same cannot be said for other browsers.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix/) / [Hexagony](https://github.com/m-ender/hexagony), 31 bytes
```
t;./e;_a]"kcirt">o?@;=v=./r;\;/
```
[Trick it out!](http://ethproductions.github.io/cubix/?code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw==) [Treat it online!](http://hexagony.tryitonline.net/#code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw&input=)
*Halloween themed*? Note the horrifying facts about these languages and the code:
1. If and even if you do nothing (just put no-ops), you can *never* get out of the loop that is determined to be running forever...
2. And being stuck in the middle of a 3D and a 2D programming language (Oh agony...)
3. Inside the dimensions, you'll gradually lost where you are... where you were...
4. And there is a `=v=` smiling at you which acts at no-ops in the code
Let's dig into the mystery of the hidden 31-bytes communication protocol of dimensions and terror...
## trick
When the code folds or unfolds itself... That is `cubified`, the layout looks like this:
```
      t ; .
      / e ;
      _ a ]
" k c i r t " > o ? @ ;
= v = . / r ; \ ; / . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .
```
And the main part is this part in the middle:
```
" k c i r t " > o ? @ .
. . . . . . . \ ; / . .
```
It pushes `k,c,i,r,t` onto the stack and `o` outputs and `;` pops within a loop bounded by reflectors and `?` which guides you depending on the value on the top of the stack...
## treat
All of a sudden, the code transforms from a cube to a Hexagon. (Imagine that)
```
   t ; . /
  e ; _ a ]
 " k c i r t
" > o ? @ ; =
 v = . / r ;
  \ ; / . .
   . . . .
```
And the main part is this part:
```
   t ; . /
  e ; _ a ]
 . . . . . .
. . . . @ ; =
 . . . / r ;
  . . . . .
   . . . .
```
It runs `t;` which prints `t` and hits the mirror and turns its direction to NW starting from the SE corner and hits another mirror. This runs `r;` and wraps to `e;_a` and the `]` brings it to the Instruction Pointer 1 which starts at corner NE pointing SE and hits `/` which reflects horizontally to `;` then `t`.
Then it wraps to `=`, `;`, and `@` ends the mess.
So... What is `_` doing there?
*Why* is it inside the `t` `e` `a` (the first 3 letters in the code)?
Here comes the end of the story -
it does *nothing*.
Does it sound like the end of a horror story?
[Answer]
# [#hell](http://esolangs.org/wiki/HashHell) / [Agony](http://esolangs.org/wiki/Agony), 43 bytes
So much `><>` everywhere, what is this, an April Fools challenge? Here's an answer with appropriately themed languages.
```
--<.<.<.<.<.$
io.write("trick")--+<~}~@+{+<
```
`#hell` is a subset of `LUA` which fortunately accepts `io.write` output calls. We use `LUA`'s `--` comments so that it only executes this fragment.
`Agony` is a `Brainfuck` derivative, which has the particularity to have its code and working memory on the same tape. The first line only prints 5 characters (10 cells) from the end of the code segment, where I encoded `treat` as `Agony` commands. `LUA`'s comment opening `--` modifies the value of a cell which isn't used.
[Answer]
## SQL / Javascript, 54 bytes
```
select('trick')
--a;function select(){alert("treat")}
```
Same approach as with my [QB/JS answer](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97509#97509): First line has the SQL statement, the second line has a 'comment' for SQL and a NOP for JS. Then, we define SQL's `select` statement as a valid JS function.
[Answer]
# /Brainf..k/, 143 + 3 = 146 bytes
This answer requires the `-A` flag to output in ASCII for Brain-Flak and luckily Brainfuck doesn't care about that flag so it doesn't affect the output in Brainfuck.
```
(((((()(()()()){})({}){}){}){})+++++++[<+++<(((()()()())((((({}){}){}){}){}()))[][][][]())>>-])<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)
[Try it Online!](http://brainfuck.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)
## How this works
The only overlap between the syntax of Brain-Flak and Brainfuck are the characters `<>[]`. For brain-flak this mostly means the program has to ensure an even number of stack switches `<>`. And for Brainfuck this means we need to avoid infinite loops caused by use of the `[]` monad.
The Brain-Flak code is as follows:
```
(((((()(()()()){})({}){}){}){})[<<(((()()()())((((({}){}){}){}){}()))[][][][]())>>])<[<>]<>[<>]<>>
```
Aside from the `[<<...>>]` bit in the middle and the `<[<>]<>[<>]<>>` at the end this code is pretty par for the course as far as Brain-Flak programs go. The negative around the zero (`[<...>]`) is there to create a loop for Brainfuck. The inner `<...>` is used to move the Brainfuck to an empty cell before it encounters the `[][][][]` which would loop infinitely otherwise.
The Brainfuck code is as follows:
```
+++++++[<+++<[][][][]>>-]<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>
```
Aside from the aforementioned bits this is also a pretty standard program so I will spare you the details.
[Answer]
# [><>](https://esolangs.org/wiki/Fish) / [Fishing](https://esolangs.org/wiki/Fishing), 38 bytes
```
_"kcirt"ooooo;
[+vCCCCCCCC
   `treat`N
```
For the sake of making a `><>` / `Fishing` polyglot.
It's my first piece of `Fishing` code after having played for a long time with `><>`.
My first impression : as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool !
Here the code is extremely simple : `><>` will only execute the first line, where `_` is a vertical mirror and has no effect since the fish starts swimming horizontally. It just pushes `trick` on the stack then print it before stopping.
For `Fishing`, the `_` instructs to go down. The fisherman will follow the deck that is the second line while catching the characters of the third line. These will push `treat` on the tape then print it, stopping as it reaches the end of the deck.
If erroring out is allowed, you could go down to 35 bytes with the following code which will throw an error when run as `><>` once the `trick` is printed off the stack :
```
_"kcirt">o<
[+vCCCCCCCC
   `treat`N
```
---
You should also check my themed languages answers, [#hell / Agony](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97533#97533) and [evil / ZOMBIE](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97542#97542) !
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E)/[Actually](https://github.com/Mego/Seriously), 10 bytes
```
"trick"’®Â
```
**Explanation**
**05AB1E**
```
"trick"     # push the string "trick"
       ’®Â  # push the string "treat"
            # implicitly print top of stack (treat)
```
[Try it online](http://05ab1e.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=)
**Actually**
```
"trick"     # push the string "trick"
       ’®Â  # not recognized commands (ignored)
            # implicit print (trick)
```
[Try it online](http://actually.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=)
[Answer]
# [Haskell](https://www.haskell.org/) / [Standard ML](https://en.wikipedia.org/wiki/Standard_ML), 56 bytes
```
fun putStr x=print"treat";val main=();main=putStr"trick"
```
**Haskell view**
The semicolons allow multiple declarations in one line and act like linebreaks, so we get
```
fun putStr x=print"treat"
val main=()
main=putStr"trick"
```
A Haskell program is executed by calling the `main` function, so in the last row `putStr"trick"` is executed which just prints `trick`.
The first two rows are interpreted as function declarations following the pattern `<functionName> <argumentName1> ... <argumentNameN> = <functionBody>`. So in the first row a function named `fun` is declared which takes two arguments named `putStr` and `x` and the function body `print"treat"`. This is a valid Haskell function with type `fun :: t -> t1 -> IO ()`, meaning it takes an argument of an arbitrary type `t` and a second one of some type `t1` an then returns an IO-action. The types `t` and `t1` don't matter as the arguments aren't used in the function body. The IO-action type results from `print"treat"`, which prints `"treat"` to StdOut (notice the `"`, that's why `putStr` instead of `print` is used in `main`). However as it's only a function declaration, nothing is actually printed as `fun` is not called in `main`.
The same happens in the second line `val main=();`, a function `val` is declared which takes an arbitrary argument named `main` and returns *unit*, the empty tuple `()`. It's type is `val :: t -> ()` (Both the value and the type of *unit* are denoted with `()`).
[Try it on Ideone.](http://ideone.com/MYQF7C)
---
**Standard ML view**
[Standard ML](https://en.wikipedia.org/wiki/Standard_ML) is a primarily functional language with a syntax related to, but not the same as Haskell. In particular, function declarations are prefixed with the keyword `fun` if they take any arguments, and the keyword `val` if they don't. Also it's possible to have an expression at top level (meaning not inside any declaration) which is executed when the program is run. (In Haskell writing `1+2` outside a declaration throws a `naked expression at top level`-error). Finally the symbol for testing equality is `=` instead of `==` in Haskell. (There are many more differences, but those are the only ones that matter for this program.)
So SML sees two declarations
```
fun putStr x=print"treat";
val main=();
```
followed by an expression
```
main=putStr"trick"
```
which is then evaluated. To determine whether `main` equals `putStr"trick"`, both sides have to be evaluated and both must have the same type, as SML (as well as Haskell) is statically typed.
Let us first have a look at the right side: `putStr` is not a library function in SML, but we declared a function named `putStr` in the line `fun putStr x=print"treat";` - it takes an argument `x` (this is the string `"trick"` in our case) and immediately forgets it again, as it does not occur in the function body. Then the body `print"treat"` is executed which prints `treat` (without enclosing `"`, SML's `print` is different from Haskell's `print`).
`print` has the type `string -> unit`, so `putStr` has the type `a -> unit` and therefore `putStr"trick"` has just type `unit`. In order to be well-typed, `main` must have type `unit` too. The value for *unit* is in SML the same as in Haskell `()`, so we declare `val main=();` and everything is well-typed.
[Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMUVp1b0JYWWRRNmc)
Note: The output in the console is
```
val putStr = fn : 'a -> unit
val main = () : unit
treatval it = true : bool
```
because in [SML\NJ](http://smlnj.org/) the value and type of every statement is displayed after each declaration. So first the types of `putStr` and `main` are shown, then the expressions gets evaluated causing `treat` to be printed, then the value of the expression (`true` as both sides of `=` are `()`) is bound to the implicit result variable `it` which is then also displayed.
[Answer]
# Ruby / C, ~~64~~ ~~62~~ ~~51~~ 48 bytes
```
#define tap main()
tap{puts(0?"trick":"treat");}
```
### What Ruby sees:
```
tap{puts(0?"trick":"treat");}
```
The `tap` method takes a block and executes it once. It's a short identifier that we can create a `#define` macro for in C. It also allows us to put a braces-enclosed block in the shared code, even though Ruby doesn't allow `{}`s in most contexts.
The only falsy values in Ruby are `false` and `nil`. In particular, 0 is truthy. Thus, Ruby will print "trick."
### What C sees (after the pre-processor):
```
main(){puts(0?"trick":"treat");}
```
0 is falsy in C, so C will print "treat."
2 bytes saved thanks to daniero.
[Answer]
## QBasic / JavaScript, ~~51~~ 44 bytes
```
'';PRINT=a=>{alert("Treat")}
PRINT("Trick")
```
In QBasic, it prints the second line and doesn't execute the first line because it's believed to be a comment (thank you '). In JS, it calls the function PRINT, which is defined on the first line, right after the JS NOP `'';`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) / [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
0000000: FE 22 74 52 69 63 6B 22 3F 37 29 FB ED 35                ."tRick"?7)..5
```
A fun one using Jelly's string compression.
**Jelly: treat**
```
“"tRick"?7)»ḣ5
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxylkqDM5Gwle3PNQ7sf7lhs@v8/AA "Jelly – Try It Online")
**05AB1E: trick**
```
þ"tRick"?7)ûí5
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8D6lkqDM5Gwle3PNw7sPrzX9/x8A "05AB1E – Try It Online")
**How it works**
In Jelly `“"tRick"?7)»` is a compressed string that returns `'Treatment dormy/ Orly awry'`. `ḣ5` takes the first five characters, printing `Treat`
In 05AB1E `þ` doesn't affect the program. `"tRick"` is a literal string. `?` prints this string then the rest of the program (`7)ûí5`) doesn't have any effect either.
I used [this](https://tio.run/##Dc9nV5JhGAfwr2I0bS@zrbazbXsPs0Jp27B1bh4RUbMBVKhADEVRVDYP03OuPw@dk@fchz6C1xd54t3v7a@zw2Tq0XVjMysRuFqX8kM1sDmp6zoLt6G7zdjeZWhqrKf8khps0P94/tplTMZlQiZlSqZlRqp11XhVrRaqxX@KdEindMmsDMowD/jYNsi2YbZ5WTGzorDSy4qFlT5WrHXLDMtXrFy1ek392nXrN2zctHnL1m3bG3Y07ty1e8/effubmlsOHDx0@MjRY8dbT5w8dfrM2XNt5y9cvHT5ytVr12/cvHX7zt177fc7Hjx8ZOzsMj1@8vTZ8xcvu1@9fvO25937Dx8/VVK1hhxjMVqxs/CyCLHwsfAvWllEtZqymr1s1YqVdFmwcLEYqW1ZeFgEWDhYOBfdbAlofhY5zVHu10qaWjaTnwIUpHGaoBBN0hSFaZpmKCLzNEfzFKUYxSlBSUpRmjKkUpZylKcCFalECxAwQ0EvLOiDFf2wYQCDGMJnDOMLvuIbvsMOB5z4gZ/4BRdGMIoxuOGBF7/hgx8BBDGOCYQwiSmEMY0ZRDCLOcwjihjiSCCJFNLIQEUWOeRRQBElLPwH) to convert from Jelly's code page to 05AB1E's code page. [This](https://tio.run/##DdHnUlNRGEbhW8FYsTfEDtjFjr0XBA3EjgXb7BxCCCCWJGqAJKZAIBAgPSeVme/NiTMysydegt@NHPPv@btmdXWYTL26bmxmJcLm5L/8cA1wteq6jpKhp83Y3m1oaqxHHnMN@m/PH7uMybhMyKRMybTMSLWuGq@q1UK1@FeRDumULpmVQRnmQR/bhtg2wjYvK2ZWFFb6WLGw0s@KtW6ZYfmKlatWr6lfu279ho2bNm/Zum17w47Gnbt279m7b39Tc8uBg4cOHzl67HjriZOnTp85e67t/IWLly5fuXrt@o2bt27fuXuv/X5H54OHxq5u06PHT54@e/6i5@Wr12963757/@FjJVWLkOMsxip2Fl4WIRY@Fv4lK4uoVlNWs5etWrGSLgsWLhajLNwsPCwCLBwsnEtutgQ0P4uc5igPaCVNLZvJTwEK0gRNUoimaJrCNEOzFJF5mqcFilKM4pSgJKUoTRlSKUs5ylOBilSiRQiYoaAPFvTDigHYMIghDOMTRvAZX/AV32CHA058xw/8hAujGMM43PDAi1/wwY8AgpjAJEKYwjTCmMEsIpjDPBYQRQxxJJBECmlkoCKLXG1bAUWUsPgf) does the reverse in case anyone is interested.
Jelly code page is [here](https://github.com/DennisMitchell/jelly/wiki/Code-page).
05AB1E code page is [here](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Answer]
# [ShapeScript](http://github.com/DennisMitchell/shapescript) / [Foo](http://esolangs.org/wiki/Foo), 13 bytes
```
'trick'"treat
```
**Try it online!** [trick](http://shapescript.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=) | [treat](http://foo.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=)
### How it works
ShapeScript is parsed character by character. When EOF is hit without encountering a closing quote, nothing is ever pushed on the stack. `'trick'` does push the string inside the quotes, which is printed to STDOUT implicitly.
Foo doesn't have any commands assigned to the characters is `'trick'`, so that part is silently ignored. It does, however, print anything between double quotes immediately to STDOUT, even if the closing quote is missing.
[Answer]
## Ruby / Perl, 21 bytes
```
print"trick"%1||treat
```
### Perl
Calculates `"trick" % 1` which is `0 % 1` so the `||` sends `treat` to `print` instead, since Perl accepts barewords.
### Ruby
Formats the string `"trick"` with the argument `1`, which results in `"trick"` which is truthy, so the `||` isn't processed.
[Answer]
# [MATL](https://github.com/lmendo/MATL) / [CJam](https://sourceforge.net/projects/cjam/), 17 bytes
```
'TRICK'%];"TREAT"
```
In MATL this [outputs](http://matl.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TRICK`. In CJam it [outputs](http://cjam.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TREAT`.
## Explanation
### MATL
```
'TRICK'         Push this string
%];"TREAT"      Comment: ignored
                Implicit display
```
### CJam
```
'T              Push character 'T'
R               Push variable R, predefined to empty string
I               Push variable I, predefined to 18
C               Push variable C, predefined to 12
K               Push variable K, predefined to 20
'%              Push character '%'
]               Concatenate stack into an array
;               Discard
"TREAT"         Push this string
                Implicit display
```
[Answer]
# Objective-C / C, 50 bytes
```
puts(){printf("trick");}main(){printf("treat\n");}
```
Objective-C got candy and [prints treat](http://ideone.com/Hdt3fO), but C didn't and [prints trick](http://ideone.com/eRC6M2).
### How it works
I don't know a lot about **Objective-C**, but it does what we'd reasonably expect in this situation. The re-definition of `puts` doesn't affect the output since we never call the function, and `main` prints **treat** and a linefeed to STDOUT.
You might expect **C** to do the same, but at least gcc 4.8, gcc 5.3, and clang 3.7 don't.
Since we do not need the *real* **printf** (which takes a format string and additional arguments) and the string to be printed ends with a linefeed, we can use **puts** instead. **puts** is slightly faster than **printf** (which has to analyze its arguments before printing), so unless we redefine the function **printf** as well, the compiler optimizes and replaces the call to **printf** with a call to **puts**. Little does the compiler know that calling `puts` with argument `"treat"` will print **trick** instead!
Not including **stdio.h** is crucial here, since defining **puts** would require using the same type it has in the header file (`puts(const char*)`).
Finally, it is noteworthy that the call to **printf** in **puts** passes a string *without* a trailing linefeed. Otherwise, the compiler would "optimize" that call as well, resulting in a segmentation fault.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) / [pl](http://github.com/quartata/pl-lang), 12 bytes
```
0000000: 74 72 65 61 74 0a 7f fe 00 ba 49 fb                 treat.....I.
```
This is the program displayed using [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page).
```
treatµ
“¡ṾI»
```
[Try it online!](http://jelly.tryitonline.net/#code=dHJlYXTCtQrigJzCoeG5vknCuw&input=)
This is the program displayed using [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).
```
treat
⌂■␀║I√
```
[Try it online!](http://pl.tryitonline.net/#code=dHJlYXQK4oyC4pag4pCA4pWRSeKImg&input=)
Both programs have been tested locally with the same 12 byte file, so this is a proper polyglot.
### How it works
In Jelly, every line defines a *link* (function); the last line defines the *main link*, which is executed automatically when the program is run. Unless the code before the last `7f` byte (the linefeed in Jelly's code page) contain a parser error (which would abort execution immediately), they are simply ignored. The last line, `“¡ṾI»` simply indexes into Jelly's dictionary to fetch the word **trick**, which is printed implicitly at the end of the program.
I don't know much about pl, but it appears that the interpreter only fetches one line of code and ignores everything that comes after it. As in Perl, barewords are treated as strings, so `treat` prints exactly that.
[Answer]
## Batch/sh, 30 bytes
```
:;echo Treat;exit
@echo Trick
```
Explanation. Batch sees the first line as a label, which it ignores, and executes the second line, which prints Trick. The @ suppresses Batch's default echoing of the command to stdout. (Labels are never echoed.) Meanwhile sh sees the following:
```
:
echo Treat
exit
@echo Trick
```
The first line does nothing (it's an alias of `true`), the second line prints Treat, and the third line exits the script, so the @echo Trick is never reached.
[Answer]
# sed / Hexagony 32 bytes
```
/$/ctrick
#$@$a</;r;e;/t;....\t;
```
---
# sed
[Try it Online!](http://sed.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=)
The first line prints `trick` if there is an empty string at the end of input. (sed doesn't do anything if there isn't input, but a blank line on stdin is allowed in this case)
**Example run:**
```
$ echo | sed -f TrickOrTreat.sed
trick
```
---
# Hexagony
[Try it Online!](http://hexagony.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=)
The first `/` redirects the instruction pointer up and the the left, so it wraps the the bottom left, skipping the text used for sed. It reuses the r from the sed code and runs a few others to no effect. The expanded hex looks like this:
```
   / $ / c
  t r i c k
 # $ @ $ a <
/ ; r ; e ; /
 t ; . . . .
  \ t ; . .
   . . . .
```
**Output:**
```
treat
```
[Answer]
# C# / Java
This probably doesn't qualify as it doesn't run on its own, but the challenge has reminded me of a quirk in how C# and Java handle string comparison differently that you can have some fun with for code obfuscation.
The following function is valid in C# and Java, but will return a different value...
```
public static String TrickOrTreat(){
    String m = "Oct";
    String d = "31";
    return m + d == "Oct31" ? "Trick" : "Treat";
}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) / Brain-Flueue, ~~265 253 219 165 139 115 113~~ 101 bytes
Includes +1 for `-A`
Thanks to Wheat Wizard for going back and forth, golfing a few bytes off each others code, with me.
```
((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){}
```
Brain-Flak: [Try it online!](https://tio.run/nexus/brain-flak#NYoxDoBQCEOvQ4d/CM9BGL6DifHHwZVwdiwYgaY0ryk1qAVEjcHDg7@HaKePwZo27KsS1FpaHcNfppFSaoQemTm2HGt/5nkfa14v)
Brain-Flueue: [Try it online!](https://tio.run/nexus/brain-flak#NYpBCsBACAO/sznsI/oO8dDCFgpLD4U9iW@30VI1xDCJloNcoIkymJvzN29S6WPQogXrsgTRkmRH8ZdppJQooXlE9C36PJ79us@5xhov)
**Explanation:**
The first section lists the values that Brain-Flak sees.
When it switches to Brain-Flueue, I start listing the values as Brain-Flueue sees them.
```
# Brain-Flak
(
 (((()()()))             # Push 3 twice
  ([]                    # Use the height to evaluate to 2
   (
    (({}{}))             # Use both 3s to push 6 twice
    ({}                  # Use one of those 6s to evaluate to 6
     ([((({}()())))]     # Use the other 6 to push 8 three times and evaluate to -8
      ([](({}{}){}){}{}) # Use all three 8s to push 75
     )                   # The -8 makes this push 67
    )                    # The 6 makes this push 73
   [])                   # Use the height and the 6 to push 82
  )                      # Use the 2 to push 84
# Brain-flueue
 [])     # Use the height and 3 to push 84
[()()])  # Push 82
({}()()) # 67 is at the front of the queue, so use that to push 69
{}       # Pop one from the queue
({})     # 65 is next on the queue so move to the end
({}[][]) # 74 is next, so use that and the height to push 84
{}       # Pop that last value from TRICK
```
[Answer]
## PowerShell / Foo, 14 bytes
```
'trick'#"treat
```
The `'trick'` in PowerShell creates a string and leaves it on the pipeline. The `#` begins a comment, so the program completes and the implicit `Write-Output` prints `trick`.
In Foo, [(Try it Online!)](http://foo.tryitonline.net/#code=J3RyaWNrJyMidHJlYXQ&input=), the `'trick'` is ignored, the `#` causes the program to sleep for `0` seconds (since there's nothing at the array's pointer), then `"treat` starts a string. Since EOF is reached, there's an implicit `"` to close the string, and that's printed to stdout.
]


[Question]
      [
Given a number *N*, draw a left aligned *N*x*N* board of numbers, leaving 1 blank (as a space) (I will show diagrams with *N*=5)
```
   2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
```
Your job is to construct the Sieve of Eratosthenes, step by step. First, start with 2. It's prime, so leave it there, and replace all other numbers divisible by 2 with the proper number of spaces.
```
   2  3     5
   7     9
11    13    15
   17    19
21    23    25
```
Next, go to the next unprinted number (`3` in this case) and do the same.
```
   2  3     5
   7
11    13
   17    19
      23    25
```
And so on, until you reach *N*.
You need to first print the complete grid, and every time you go to a new number, print the board with the multiples removed. Make sure you print a blank line in between!
## Examples
Text in parenthesis `()` are just for reference, you don't need to print it
*N* = 2:
```
  2 (complete grid)
3 4
  2 (remove multiples of 2)
3
```
*N* = 3:
```
  2 3 (complete grid)
4 5 6
7 8 9
  2 3 (remove multiples of 2)
  5
7   9
  2 3 (remove multiples of 3)
  5
7
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṿ€“1“ ”ys³G
>®i©1ḍoṛ®¦
²R;1©ÇÐĿÑ€Y
```
[Try it online!](http://jelly.tryitonline.net/#code=4bm-4oKs4oCcMeKAnCDigJ15c8KzRwo-wq5pwqkx4biNb-G5m8KuwqYKwrJSOzHCqcOHw5DEv8OR4oKsWQ&input=&args=NQ)
### How it works
```
²R;1©ÇÐĿÑ€Y  Main link. Argument: n (integer)
²            Yield n².
 R           Range; yield [1, ..., n²].
   1©        Yield 1 and copy it to the register.
  ;          Append 1 to the range.
             This is the initial state. Let's call it S.
     ÇÐĿ     Call the second helper link until the results are no longer unique.
             This returns all unique results as an array.
        Ṅ€   Call the first helper link on each result.
          Y  Join, separating by linefeeds.
>®i©1ḍoṛ®¦   Second helper link. Argument: S (state)
>®           Compare all integers in S with the value in the register.
  i 1        Find the first index of 1 (i.e., the first number that is greater
             than the register.
   ©         Copy the index to the register. Let's call the index p.
     ḍ       Test all numbers in S for divisibility by p. This yield 1 for
             multiples of p, 0 otherwise.
      o      Logical OR; replace 0's with the corresponding values of S.
       ṛ®¦   Replace the 0 at index p with the corresponding element of S (p).
             For the purposes of the explanation, S is now the updated state.
Ṿ€“1“ ”ys³G  First helper link. Argument: A (array)
Ṿ€           Uneval each; convert all integers in A into strings.
  “1“ ”y     Replace each string "1" with the string " ".
        s³   Split into chunks of length n (command-line argument).
          G  Grid; separate row items by spaces (left-padding since the row items
             are strings), the rows themselves by linefeeds.
```
[Answer]
# Perl, ~~250~~ ~~243~~ ~~231~~ ~~202~~ 157 bytes
```
$n=<>;@a=0..($e=$n*$n);$a[1]=$";for$p(1..$n){next if!$a[$p];for(1..$e){$a[$_]=""if!($p~~[(1,$_)]||$_%$p);printf"%-*s",1+length$e,$a[$_];say""if!($_%$n)}say}
```
[Test the current golf online!](https://goo.gl/2pXEWQ) (be sure to run as `perl -M5.010 main.pl`)
The two literal newlines each save 1 byte in place of \n.
Sample output (input of 7):
```
   2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49
   2  3     5     7
   9     11    13
15    17    19    21
   23    25    27
29    31    33    35
   37    39    41
43    45    47    49
   2  3     5     7
         11    13
      17    19
   23    25
29    31          35
   37          41
43          47    49
   2  3     5     7
         11    13
      17    19
   23
29    31
   37          41
43          47    49
   2  3     5     7
         11    13
      17    19
   23
29    31
   37          41
43          47
```
I'm positive I didn't golf it very well, so when I get home I'll take another look at it to see just how much I can shave off.
Edit 1: -7 bytes (changing "print sprintf" to the obvious "printf")
Edit 2: Saved 12 bytes by using $d explicitly in the one place it was called instead of creating a separate variable, by combining some declarations, and by eliminating one of my conditions for the `next` statement inside the first `foreach` loop by adding a space somewhere else.
An additional 29 bytes were golfed out by reworking two for loops into a single loop, eliminating two variable declarations, and turning `unless` statements into if-not statements. Declaring `my$e=$n*$n;` then replacing the three instances of $n\*$n with $e (allowing me to drop a paren for one of them) turned out to yield ±0 bytes, but I kept it in anyway.
Edit 3: Thanks to @Dada, another 40 bytes were golfed out (variable declarations, 'foreach' becoming 'for', implicit $\_ in several locations, and cutting down on the printf statement size). An additional 1 byte was shaved off by turning `if!($c%$p||$c==$p||$p==1)` into `if!($p~~[(1,$_)]||$_%$p)`. Unfortunately, the [] around the array is necessary, because the smartmatch operator ~~ is still experimental and doesn't seem to work properly on actual arrays, but does work on references to them instead. 4 more bytes were removed by removing two semicolons and an empty set of quotation marks after the last `say`.
[Answer]
# PHP, 155 Bytes
```
for(;$d++<$n=$argv[1];$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))for($i=$d*$x=$d>1;$n**2>=$i+=$d;)$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);
```
@Crypto -3 Bytes Thank You
@Titus -6 Bytes Thank You
[Try it](http://sandbox.onlinephpfunctions.com/code/4e0784d5a9a5633acbb7f18580e048d49554af0e)
First time that I use print in a after loop condition
Breakdown
```
for(;$d++<$n=$argv[1];
$x&$a[$d]<1?:print"\n".chunk_split(join($a),$n*$l))
#after loop print the grid if $d = 1 or is prime
for($i=$d*$x=$d>1;$n**2>=$i+=$d;)
$a[$i]=str_pad($x|$i<2?"":$i,$l=strlen($n**2)+1);
#fills the array at first run and replace positions with space in the next runs
```
Previous Version 174 Bytes
```
for(;$d++<=$n=$argv[1];!($d<2||$a[$d]>0)?:print chunk_split(join($a),$n*$l)."\n")for($i=$d<2?1:2*$d;$i<=$m=$n**2;$i+=$d)$a[$i]=str_pad($d<2?($i<2?"":$i):" ",$l=strlen($m)+1);
```
[Answer]
# R, ~~195~~ ~~191~~ ~~185~~ 204 bytes
```
f=function(N){a=b=1:N^2;i=1;a[1]="";S=sprintf;while(i<=N){for(j in b)cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),if(j%%N)"" else"\n");cat("\n");i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1]}}
```
Thanks to @Billywob for 6 extra bytes saved!
Indented, with newlines:
```
f=function(N){
   a=b=1:N^2 #Initial array
   i=1 #Turn counter
   a[1]="" #1 never shown
   S=sprintf
   while(i<=N){
      for(j in b)
         cat(a[j]<-S(S("%%-%is",nchar(N^2)),if(j==i|j%%i|i<2)a[j]else ""),
             if(j%%N)"" else"\n") #Newline at end of row
      cat("\n") #Newline between turns
      i=(grep("\\d",a[-(1:i)],v=T)[1]:1)[1] #Select next prime as next i
   }
}
```
Usage:
```
> f(2)
  2
3 4
  2
3
> f(3)
  2 3
4 5 6
7 8 9
  2 3
  5
7   9
  2 3
  5
7
> f(9)
   2  3  4  5  6  7  8  9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80 81
   2  3     5     7     9
   11    13    15    17
19    21    23    25    27
   29    31    33    35
37    39    41    43    45
   47    49    51    53
55    57    59    61    63
   65    67    69    71
73    75    77    79    81
   2  3     5     7
   11    13          17
19          23    25
   29    31          35
37          41    43
   47    49          53
55          59    61
   65    67          71
73          77    79
   2  3     5     7
   11    13          17
19          23
   29    31
37          41    43
   47    49          53
            59    61
         67          71
73          77    79
   2  3     5     7
   11    13          17
19          23
   29    31
37          41    43
   47                53
            59    61
         67          71
73                79
> f(12)
    2   3   4   5   6   7   8   9   10  11  12
13  14  15  16  17  18  19  20  21  22  23  24
25  26  27  28  29  30  31  32  33  34  35  36
37  38  39  40  41  42  43  44  45  46  47  48
49  50  51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70  71  72
73  74  75  76  77  78  79  80  81  82  83  84
85  86  87  88  89  90  91  92  93  94  95  96
97  98  99  100 101 102 103 104 105 106 107 108
109 110 111 112 113 114 115 116 117 118 119 120
121 122 123 124 125 126 127 128 129 130 131 132
133 134 135 136 137 138 139 140 141 142 143 144
    2   3       5       7       9       11
13      15      17      19      21      23
25      27      29      31      33      35
37      39      41      43      45      47
49      51      53      55      57      59
61      63      65      67      69      71
73      75      77      79      81      83
85      87      89      91      93      95
97      99      101     103     105     107
109     111     113     115     117     119
121     123     125     127     129     131
133     135     137     139     141     143
    2   3       5       7               11
13              17      19              23
25              29      31              35
37              41      43              47
49              53      55              59
61              65      67              71
73              77      79              83
85              89      91              95
97              101     103             107
109             113     115             119
121             125     127             131
133             137     139             143
    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
49              53                      59
61                      67              71
73              77      79              83
                89      91
97              101     103             107
109             113                     119
121                     127             131
133             137     139             143
    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
                53                      59
61                      67              71
73                      79              83
                89
97              101     103             107
109             113
121                     127             131
                137     139             143
    2   3       5       7               11
13              17      19              23
                29      31
37              41      43              47
                53                      59
61                      67              71
73                      79              83
                89
97              101     103             107
109             113
                        127             131
                137     139
```
[Answer]
# Python 2, ~~199 202~~ 201 bytes
+3 bytes (I wasn't stopping early)
-1 byte thanks to @Oliver (missed a space)
```
def f(n,p={()}):
 m=n*n;g=['']+[[i,''][any(i>n and i%n<1for n in p)]for i in range(2,m+1)];x=min(set(g)-p);i=0
 while i<m+n:print' '.join('%%%ds'%-len(`m`)%v for v in g[i:i+n]);i+=n
 if x<=n:f(n,p|{x})
```
**[repl.it](https://repl.it/EBNG/4)**
[Answer]
# Groovy, ~~201~~ ~~195~~ 191 Bytes
```
{n->a=(1..n*n).toArray();y={a.collect{(it?"$it":"").padRight((""+n*n).size())}.collate(n).each{println it.join(" ")}};a[0]=0;y(a);(2..n).each{b->(b+1..n*n).each{if(it%b==0){a[it-1]=0}};y(a)}}
```
This is an absolute cluster... The left-align murdered my byte count. But hey, it works. Here's the output for 4:
```
   2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
   2  3
5     7
9     11
13    15
   2  3
5     7
      11
13
   2  3
5     7
      11
13
```
# Ungolfed:
```
{
    n->
    a = (1..n*n).toArray();                           // Create initial array.
    y = {                                             // Createa  printing utility closure.
        a.collect {                                   // Create an array collection of...
            (it ? "$it":"").padRight((""+n*n).size()) // If 0, store "", else store number & right pad it.
        }.collate(n).each{                            // Collate by n (break into nxn grid).
            println it.join(" ")                      // print each separated by spaces.
        }
    };
    a[0]=0;                                           // Remove first element.
    y(a);                                             // Print initial status.
    (2..n).each{                                      // From 2 to n...
        b->
        (b+1..n*n).each{                              // From current number + 1 to end of grid...
            if(it%b==0){                              // If current grid position is divisible...
                a[it-1]=0                             // Replace with 0.
            }
        }
        y(a)                                          // Print it.
    }
}
```

[Answer]
# Perl, ~~115~~ ~~114~~ ~~113~~ 112 bytes
Includes +1 for `-a`
Run with input number on STDIN:
```
perl -M5.010 sieving.pl <<< 7
```
`sieving.pl`:
```
#!/usr/bin/perl -a
$_*=$_;$a.="$_"x$|++|$"x"@+".($_%"@F"?$":$/)for/\d+/..$_;*_=a;s^^$$_++||say;$.++;s//$&%$.|$&==$.?$&:$&&$_/eg^eg
```
Needs a recent enough perl so that `-a` implies `-n`. If your perl is too old add a `-n` option.
Prints a trailing newline which is allowed.
[Answer]
## JavaScript (ES6), ~~190~~ 189 bytes
Directly prints to the console.
```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''}    `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))
```
### Demo
```
f=(w,k=1,a=[...Array(w*w)].map((_,n)=>n&&n+1))=>k++<=w&&(k==2|a[k-2]&&console.log(a.map((n,x)=>`${n||''}    `.slice(0,`_${w*w}`.length)+(++x%w?'':`
`)).join``),f(w,k,a.map(n=>n==k|n%k&&n)))
f(5)
```
[Answer]
## Batch, 464 bytes
```
@echo off
set/an=%1,s=n*n,t=s,c=1
set p=
:l
set/ac+=1,t/=10
set p= %p%
if %t% gtr 0 goto l
for /l %%i in (1,1,%1)do call:i %%i
exit/b
:i
set l=
set/af=0
call:f %1 %1
if %f%==0 for /l %%j in (1,1,%s%)do call:j %1 %%j
exit/b
:j
set/am=%2,f=!(m-1),g=%2%%n
call:f %1 %2
if %f% gtr 0 set m=
set m=%m% %p%
call set l=%%l%%%%m:~0,%c%%%
if %g%==0 echo(%l%&set l=
if %2==%s% echo(
exit/b
:f
for /l %%l in (2,1,%1)do if %%l neq %2 set/af+=!(%2%%%%l)
```
This was somewhat laborious. Explanation: Starts by squaring `n` so that it can calculate the desired column width `c`, and the appropriate amount of padding `p`, using the loop `:l`. The outer loop from `1` to `n` then runs once for each grid, calling the subroutine `:i`. First the value is checked to see whether it is 1 or prime; if not then that grid is skipped. The inner loop from `1` to `n*n` then handles the rows and columns of the grid, calling the subroutine `:j`. Each value is checked to see whether it is one of the prime numbers found so far, or if none of the prime numbers found so far divide it. If so then the value is concatenated to the output buffer, which is then padded to the desired column width. The buffer is printed and cleared every `n` lines, and an extra blank line is added at the end of the grid. The `:f` label denotes the factor-checking subroutine; f(x,y) adds 1 to `f` for each integer between 2 and `x` that divides `y`, excluding `y` itself.
[Answer]
# J, 125 bytes
```
p=:3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'
```
This is explicit, not tacit J, but there should be a way to golf it tacitly.
## Usage
```
   p =: 3 :'}."1,./('' '',.>)"1|:(-%:#y)]\((a:"_)`(<@":)@.*)"+y'
   f =: 3 :'p@>~.|.(]*](*@|~+.=)({[:I.*){])&.>/\.(<"+i.-y),<]`>:@.*i.*:y'
   f 2
  2
3 4
  2
3
   f 3
  2 3
4 5 6
7 8 9
  2 3
  5
7   9
  2 3
  5
7
   f 4
   2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
   2  3
5     7
9     11
13    15
   2  3
5     7
      11
13
   f 5
   2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
   2  3     5
   7     9
11    13    15
   17    19
21    23    25
   2  3     5
   7
11    13
   17    19
      23    25
   2  3     5
   7
11    13
   17    19
      23
```
[Answer]
# Mathematica, 133 bytes
```
Grid[#,Alignment->Left]~Print~"
"&/@FoldList[#/.(##|1&@@(2~r~i#2)->Null)&,(r=Range)[i=#^2]~Partition~#/.Rule[1,],Prime@r@PrimePi@#];&
```
[Answer]
# PHP, ~~155~~ ~~150~~ ~~147~~ ~~145~~ ~~142~~ 140 bytes
```
for(;$k++<$n=$argv[1];)if($k<2||$a[$k]){for($i=0;$i++<$n*$n;)echo$a[$i]=$k>1?$i>$k&$i%$k<1?"":$a[$i]:($i<2?"":$i),"\t\n"[$i%$n<1];echo"\n";}
```
**breakdown**
```
for(;$k++<$n=$argv[1];)
    if($k<2||$a[$k])    // if first iteration or number unprinted ...
{
    for($i=0;$i++<$n*$n;)
        echo
            $a[$i]=$k>1
                ?$i>$k&$i%$k<1
                    ?""         // sieve
                    :$a[$i]     // or copy value
                :($i<2?"":$i)   // first iteration: init grid
            ,
            // append tab, linebreak every $n columns
            "\t\n"[$i%$n<1]
        ;
    // blank line after each iteration
    echo"\n";
}
```
]


[Question]
      [
# Introduction
A bell tower will ring its bells every hour, `n` times, with `n` being the the current hour on a 12 hour clock.
For example, a bell will ring 5 times at 5pm, and 10 times at 10am.
# Task
Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times
# Examples
```
"10am-12pm"
10+11+12= 33
[01:00, 05:00]
1+2+3+4+5 = 15
[11, 15]
11+12+1+2+3 = 29
[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
```
If the start is the same as the end then the you simply just ouput the number of chimes for that hour:
```
[5pm, 5pm]
5 = 5
```
As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.
Note:
* inputs may span from the afternoon of one day to the morning of the next.
* the difference between the two times will never be more than 24 hours.
* input is flexible so long as you clearly state what format your input is.
* your input must have a **clear** distinction between AM and PM.

[Answer]
# JavaScript (ES6), ~~38~~ 35 bytes
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
```
Recursively adds the current number of bell rings to the total. Called like `f(11,15)`; midnight is represented as `24`. I got part of the `~-` trick from [@xnor's Python answer](https://codegolf.stackexchange.com/a/95261/42545).
## Test snippet
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
g=(x,y)=>console.log("x:",x,"y:",y,"result:",f(x,y))
g(10,12)
g(1,5)
g(11,15)
g(22,10)
```
```
<input id=A type="number" min=1 max=24 value=9>
<input id=B type="number" min=1 max=24 value=17>
<button onclick="g(A.value,B.value)">Run</button>
```
### Non-recursive version (Firefox 30+), 56 bytes
```
(x,y,t=0)=>[for(_ of Array((y-x+25)%24))t+=x++%12||12]|t
```
Equivalent to the following ES6 function:
```
(x,y,t=0)=>[...Array((y-x+25)%24))].map(_=>t+=x++%12||12)|t
```
[Answer]
# Python 2, 46 bytes
```
f=lambda x,y:(x%12or 12)+(x-y and f(-~x%24,y))
```
Based on my JS answer. The recursive formula **f** for the solution is defined as so:
1. Start with two integers **x** and **y**.
2. Take **x mod 12**; if this is 0, take **12** instead.
3. If **x != y**, add the result of **f(x+1 mod 24, y)**.
[Answer]
# Python 2, ~~59~~ 54 bytes
```
a=lambda x,y:sum(1+i%12for i in range(x-1,y+24*(x>y)))
```
Equivalent to
```
summ=0
if start > end:
    end+=24
for hour in range(start-1,end):
    summ +=1+hour%12
print summ
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
With a lot of help from *Emigna*.
```
-24%Ý¹+<12%>O
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=LTI0JcOdwrkrPDEyJT5P&input=MjMKMQ)
[Answer]
## Python, 42 bytes
```
f=lambda a,b:~-a%12-~(b-a and f(-~a%24,b))
```
A recursive function that takes two numbers from 0 to 23. Expanding the `~x`'s to `-x-1` gives
```
f=lambda a,b:(a-1)%12+1+(b-a and f((a+1)%24,b))
```
The expression `(a+1)%12+1` converts a time to the number of rings `1` to `12`. Then, the lower bound is incremented modulo 24 and the function for the recursive result is added. That is, unless the current hour is the end hour, in which case we stop.
I've been trying to write a purely arithmetical solution instead, but so far I've only found long and messy expressions.
[Answer]
## Haskell, 48 43 bytes
```
s%e=sum[mod x 12+1|x<-[s-1..e+23],x<e||s>e]
```
Usage is `startHour % endHour`, with both inputs given in 24-hr format.
*edit: added @xnor's improvement, saving 5 bytes*
[Answer]
# C#, 73 bytes
```
a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
```
Acceptable input: integers in range [0,23].
**This solution does not use LINQ.**
---
Full program with test cases:
```
using System;
namespace HowManyTimesABellTowerRings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

            Console.WriteLine(f(10)(12));   //33
            Console.WriteLine(f(1)(5));     //15
            Console.WriteLine(f(11)(15));   //29
            Console.WriteLine(f(22)(10));   //88
            Console.WriteLine(f(10)(10));   //10
            Console.WriteLine(f(11)(10));   //156
            Console.WriteLine(f(0)(23));    //156
            Console.WriteLine(f(22)(1));    //34
        }
    }
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17 16 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>×24+⁹⁸r’%12‘S
```
**[TryItOnline](http://jelly.tryitonline.net/#code=PsOXMjQr4oG54oG4cuKAmSUxMuKAmFM&input=&args=MjM+MQ)**
How?
```
>×24+⁹⁸r’%12‘S - Main link: a, b (24 hr integers, midnight may be 0 or 24)
>              - a>b? (1 if true, 0 if false)
 ×24           - times 24 (24 if a>b, else 0)
    +⁹         - add to b (b+24 if a>b, else b)
      ⁸        - a
       r       - range(a, b+24 or b) ([a,a+1,...,b+24 or b])
        ’      - decrement (vectorises) ([a-1,a,...,b+23 or b-1])
         %12   - mod 12 (vectorises) (number of tolls at each occurrence - 1)
            ‘  - increment (vectorises) (number of tolls at each occurrence)
             S - sum
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
yy>24*+&:12X\s
```
Input format is as in the third example in the challenge, that is, two numbers in 24-hour format.
[Try it online!](http://matl.tryitonline.net/#code=eXk-MjQqKyY6MTJYXHM&input=MjIKMTA)
### Explanation
Take inputs `22`, `10` as an example.
```
yy      % Take two inputs implicitly. Duplicate both
        %   STACK: 22, 10, 22, 10
>       % Is the first greater than the second?
        %   STACK: 22, 10, 1
24*     % Multiply by 24
        %   STACK: 22, 10, 24
+       % Add
        %   STACK: 22, 34
&:      % Binary range
        %   STACK: [22 23 24 25 26 27 28 29 30 31 32 33 34]
12X\    % Modulo 12, 1-based
        %   STACK: [10 11 12 1 2 3 4 5 6 7 8 9 10]
s       % Sum of array
        %   STACK: 88
        % Implicitly display
```
[Answer]
# PHP, 90 Bytes
Input format '[1,24]' between 1 and 24
In this challenge that I am hate why PHP loose against other languages. I prefer to show all my ideas. Maybe an other PHP Crack finds a shorter solution.
```
<?list($f,$g)=$_GET[b];for($i=$f;$i-1!=$g|$f>$g&!$c;$s+=$i++%12?:12)$i<25?:$c=$i=1;echo$s;
```
99 Bytes
```
<?for($i=($b=$_GET[b])[0],$c=($d=$b[1]-$b[0])<0?25+$d:$d+1;$c--;$s+=$i++%12?:12)$i<25?:$i=1;echo$s;
```
113 Bytes a way with min and max
```
<?for($i=min($b=$_GET[b]);$i<=$m=max($b);)$s+=$i++%12?:12;echo($b[0]>$b[1])?156-$s+($m%12?:12)+($b[1]%12?:12):$s;
```
okay this crazy idea works with an array 149 Bytes
fills the array `$y[0]` and `$y[1]` if `$_GET["b"][0]<=$_GET["b"][1]`
if `$y[1]` is `null` we can sum this array `array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1))`
```
<?for(;++$i<25;)$y[$i>=($b=$_GET[b])[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($y[1]??array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1)));
```
This could be golfed down 124 Bytes
```
<?for(;++$i<25;)$x[($v=($b=$_GET[b])[0]>$b[1])?$i<$b[0]&$i>$b[1]:$i>=$b[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($x[!$v]);
```
Now at this point we can reduce the array with only two ints 101 Bytes
Make 2 sums `$x[0]` and `$x[1]`
`list($f,$g)=$_GET[b];`
if `$v=($f>$g`
then add value to `$x[$i<$f&$i>$g]`
else add value to `$x[$i>=$f&$i<=$g]`
the output will be find by case `echo$x[!$v];`
```
<?list($f,$g)=$_GET[b];for(;++$i<25;)$x[($v=$f>$g)?$i<$f&$i>$g:$i>=$f&$i<=$g]+=$i%12?:12;echo$x[!$v];
```
After that i found a way to calculate the result directly 112 Bytes
```
<?list($x,$y)=$_GET[t];echo(($b=$x>$y)+(($x-($s=$x%12?:12)^$y-($t=$y%12?:12))xor$b))*78-($s*($s-1)-$t*($t+1))/2;
```
recursive 103 Bytes
```
<?list($x,$y)=$_GET[t];function f($x,$y){return($x%12?:12)+($x-$y?f(++$x<25?$x:1,$y):0);}echo f($x,$y);
```
[Answer]
# PHP, 69 bytes
```
list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;
```
The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.
Takes input as 24 hour times (fine with either 0 or 24). Run like:
```
php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18
```
[Answer]
# Java, ~~72~~ ~~71~~ ~~78~~ 76 bytes
```
Usage:
    pm:    true if first time is past 11am
    time:  first time%12
    pm2:   true if second time is past 11am
    time2: second time%12
```
**Edit**:
* ***-1** byte off. Thanks to @1Darco1*
* *Fixed function head. **+7** bytes on.*
* ***-2** bytes off. Thanks to @Kevin Cruijssen*
* ***+2** bytes on. Now `e`/`clock` is initialized.*
---
```
(a,b,c,d)->{int e=0;b+=a?12:0;d+=c?12:0;for(;b!=d;e+=b%12,b=++b%24);return e;}
```
Ungolfed:
```
public static int clock(boolean pm, int time, boolean pm2, int time2){
  int clock=0;
  time+=pm?12:0;
  time2+=pm2?12:0;
  while(time!=time2){
    clock+=time%12;
    time=++time%24;
  }
  return clock;
}
```
[Answer]
## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), ~~90~~ 47 bytes
So, here's the answer printing only the total number of bell-rings:
```
::{c=a~c>12|c=c-12]d=d+c~a=b|_Xd]a=a+1~a>24|a=1
```
Input is in range `1-24`; `a` and `b` are the inputs (`::` in the code), `c` keeps track of am/pm, `d` is the total number of rings. When we've counted down all the hours, `_Xd` terminates the program, printing `d` in the process.
---
OK, I misunderstood the question and thought the `1+2+3...=` text was part of the output, so I wrote that:
```
::{c=a~c>12|c=c-12]X=!c$Z=Z+X+@+| d=d+c~a=b|?left$$|(Z,len(Z)-1)+@ =|+!d$_X]a=a+1~a>24|a=1
```
Now, I'll go code the proper answer...
[Answer]
# Pyth - 11 bytes
```
s|R12%R12}F
```
[Test Suite](http://pyth.herokuapp.com/?code=s%7CR12%25R12%7DF&test_suite=1&test_suite_input=10%2C+12%0A1%2C+5%0A11%2C+15%0A10%2C+22%0A5%2C+5&debug=0).
[Answer]
## C#, 76 bytes
```
(a,b)=>Enumerable.Range(a,Math.Abs(b-a)+1).Select(n=>n%12==0?12:n%12).Sum();
```
[Answer]
# Perl, 36 bytes
Includes +1 for `-p`
Give start and end time in 24-hour format on a line each on STDIN:
```
toll.pl
11
15
^D
```
`toll.pl`:
```
#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{
```
[Answer]
# Java 7, 64 bytes
```
int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}
```
Recursive method based on [*@ETHproductions*'s Python 2 answer](https://codegolf.stackexchange.com/a/95259/52210). Uses a 24-hour clock input.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/EAoqZi)
```
class M{
  static int c(int x, int y){
    return (x%12 < 1
             ? 12
             : x%12)
         + (x != y
             ? c(-~x % 24, y)
             : 0);
  }
  public static void main(String[] a){
    System.out.println(c(10, 12));
    System.out.println(c(1, 5));
    System.out.println(c(11, 15));
    System.out.println(c(10, 22));
    System.out.println(c(5, 5));
  }
}
```
**Output:**
```
33
15
29
88
5
```
[Answer]
## Batch, ~~168~~ 91 bytes
```
@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2
```
Edit: Saved 77 byte by switching to a closed form for the answer.
* `%1` and `%2` are the two command-line parameters
* `@` Disable Batch's default which is to echo the command
* `cmd/c` Fool Batch into immediately printing the result of the calculation
* `set/a` Perform a numeric calculation
* `x=(%1+23)%%24,` Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)
* `y=x+(%2+24-%1)%%24,` Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary
* `z=y%%12+1,` Number of bells struck at the ending hour
* `(y/12-x/12)*78+` Number of bells due to extra half days
* `z*~-z/2-` Number of bells from 1 o'clock to the ending hour inclusive
* `(x%%=12)` One less than the number of bells struck at the starting hour
* `*-~x/2` Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour
[Answer]
### C, 56 Bytes
```
f(a,b,c=0){while(b-->a){c+=b>12?b-12:b;}printf("%d",c);}
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 48 + 2 = 50 bytes
```
<v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;
```
Input is expected to be present on the stack at program start, so +2 bytes for the `-v` flag. Input is two integers specifying the hour on the 24 hour clock, so `10am - 10pm` would be given as `10 22`.
[Try it online!](http://fish.tryitonline.net/#code=PHYkJiUkLSY6JCt9OioyYwp7Pjo_IXYxLX06MSsKdj89MWw8KysxJWMrYiQKPm47&input=&args=LXYgMTA+LXYgMjI)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~45~~ 44 bytes
*Saved 1 byte, thanks to @ETHproductions*
My first foray into Cubix...
```
)$424tU4OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@;
```
Or, cubified:
```
      ) $ 4
      2 4 t
      U 4 O
I 0 I u q ; ; - ! ^ ; ^
% & 2 1 u + r r ; s s !
; s q U > & % r $ @ ; .
      . . .
      . . .
      . . .
```
You can try it out at the [online interpreter](https://ethproductions.github.io/cubix/). Input is in 24 hour format, with the end time first. For example, from 5pm to 1am the input should be `1 17`.
---
Previous version, 45 bytes:
```
)$442t\/OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@.;
```
[Answer]
# Qbasic, 112 bytes
```
input "",a
input "",b
do
if a=25 then a=1
if a<=12 then
c=c+a
else
c=c+a-12
endif
a=a+1
loop until a=b+1
print c
```
[Answer]
# Python, 73 bytes
It would be so much shorter if we didn't have to support `pm` to `am`. I use recursion to support it.
```
f=lambda a,b:sum([~-i%12+1for i in range(a,b+1)]*(a<b)or[f(a,24),f(1,b)])
```
[**Try it online**](https://repl.it/DnDQ/1)
Without supporting `pm` to `am` (45 bytes):
```
lambda a,b:sum(~-i%12+1for i in range(a,b+1))
```
]


[Question]
      [
Given a nonempty list of positive decimal integers, output the largest number from the set of numbers with the fewest digits.
The input list will not be in any particular order and may contain repeated values.
**Examples:**
```
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
```
**The shortest code in bytes wins.**

[Answer]
# Pyth, ~~7~~ ~~3~~ 6 bytes
```
eS.ml`
```
[Test Suite](http://pyth.herokuapp.com/?code=eS.ml%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0)
Explanation:
```
e      Still grab the last element
 S      Still sort
  .ml`   But prefilter the list for those with the (m)inimum length.
```
---
7 byte solution:
```
eSh.gl`
```
[Test Suite](http://pyth.herokuapp.com/?code=eSh.gl%60&test_suite=1&test_suite_input=%5B1%5D%0A%5B9%5D%0A%5B1729%5D%0A%5B1%2C+1%5D%0A%5B34%2C+3%5D%0A%5B38%2C+39%5D%0A%5B409%2C+12%2C+13%5D%0A%5B11%2C+11%2C+11%2C+1%5D%0A%5B11%2C+11%2C+11%2C+11%5D%0A%5B78%2C+99%2C+620%2C+1%5D%0A%5B78%2C+99%2C+620%2C+10%5D%0A%5B78%2C+99%2C+620%2C+100%5D%0A%5B1%2C+5%2C+9%2C+12%2C+63%2C+102%5D%0A%5B3451%2C+29820%2C+2983%2C+1223%2C+1337%5D%0A%5B738%2C+2383%2C+281%2C+938%2C+212%2C+1010%5D&debug=0)
Explanation:
```
   .g   Group items in (implicit) input by:
     l  The length of
      ` their representation
  h     Get those with the shortest length
 S      Sort the resulting list
e       and grab the last (i.e. largest) element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DL,NµÞḢ
```
Test it at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKI&input=&args=WzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF0)**
Or see all test cases also at **[TryItOnline](http://jelly.tryitonline.net/#code=REwsTsK1w57huKIKxbzDh-KCrOG5hOKCrMK1&input=&args=W1sxXSwgWzldLCBbMTcyOV0sIFsxLCAxXSwgWzM0LCAzXSwgWzM4LCAzOV0sIFs0MDksIDEyLCAxM10sIFsxMSwgMTEsIDExLCAxXSwgWzExLCAxMSwgMTEsIDExXSwgWzc4LCA5OSwgNjIwLCAxXSwgWzc4LCA5OSwgNjIwLCAxMF0sIFs3OCwgOTksIDYyMCwgMTAwXSwgWzEsIDUsIDksIDEyLCA2MywgMTAyXSwgWzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XSwgWzczOCwgMjM4MywgMjgxLCA5MzgsIDIxMiwgMTAxMF1d)**
How?
```
DL,NµÞḢ - Main link takes one argument, the list, e.g. [738, 2383, 281, 938, 212, 1010]
D       - convert to decimal, e.g. [[7,3,8],[2,3,8,3],[2,8,1],[9,3,8],[2,1,2],[1,0,1,0]]
 L      - length, e.g. [3,4,3,3,3,4]
   N    - negate, e.g [-738, -2383, -281, -938, -212, -1010]
  ,     - pair, e.g. [[3,-738],[4,-2383],[3,-281],[3,-938],[3,-212],[4,-1010]]
    µ   - make a monadic chain
     Þ  - sort the input by that monadic function, e.g [938,738,281,212,2383,1010]
          (the lists in the example are not created, but we sort over the values shown)
      Ḣ - pop and return the first element, e.g. 938
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes
Code:
```
({é¬(
```
Explanation:
```
(      # Negate the list, e.g. [22, 33, 4] -> [-22, -33, -4]
 {     # Sort, e.g. [-22, -33, -4] -> [-33, -22, -4]
  é    # Sort by length, e.g. [-33, -22, -4] -> [-4, -22, -33]
   ¬   # Get the first element.
    (  # And negate that.
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=KHvDqcKsKA&input=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ)
[Answer]
# Python 2, ~~48~~ 42 bytes
-6 bytes thanks to @Dennis (use `min` rather than `sorted`)
```
lambda l:min(l,key=lambda x:(len(`x`),-x))
```
All test cases are at **[ideone](http://ideone.com/IbYFyJ)**
Take the minimum of the list by (length, -value)
[Answer]
# Ruby, 34 bytes
```
->a{a.max_by{|n|[-n.to_s.size,n]}}
```
See it on eval.in: <https://eval.in/643153>
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
10&YlktX<=G*X>
```
[Try it online!](http://matl.tryitonline.net/#code=MTAmWWxrdFg8PUcqWD4&input=Wzc4LCA5OSwgNjIwLCAxMDBd)
Explanation:
```
  &Yl           % Log
10              % Base 10
     kt         % Floor and duplicate
       X<       % Find the smallest element
         =      % Filter out elements that do not equal the smallest element
          G     % Push the input again
           *    % Multiply (this sets numbers that do not have the fewest digits to 0)
            X>  % And take the maximum
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), ~~24~~ 16 bytes
```
O^`
O$#`
$.0
G1`
```
[Try it online!](http://retina.tryitonline.net/#code=T15gCk8kI2AKJC4wCkcxYA&input=MQoxMgo5CjYzCjUKMTAy) or [run all test cases](http://retina.tryitonline.net/#code=JShHYApPXmBcZCsKTyQjYFxkKwokLjAKIC4rCg&input=MQo5CjE3MjkKMSAxCjM0IDMKMzggMzkKNDA5IDEyIDEzCjExIDExIDExIDEKMTEgMTEgMTEgMTEKNzggOTkgNjIwIDEKNzggOTkgNjIwIDEwCjc4IDk5IDYyMCAxMDAKMSA1IDkgMTIgNjMgMTAyCjM0NTEgMjk4MjAgMjk4MyAxMjIzIDEzMzcKNzM4IDIzODMgMjgxIDkzOCAyMTIgMTAxMA).
Saved 8 bytes thanks to Martin!
The all test is using a slightly older version of the code, but the algorithm is identical. I'll update it to be closer when I get more time.
The trailing newline is significant. Sorts the numbers by reverse numeric value, then sorts them by number of digits. This leaves us with the largest number with the fewest digits in the first position, so we can just delete the remaining digits.
[Answer]
# Mathematica, ~~33~~ 31 bytes
```
Max@MinimalBy[#,IntegerLength]&
```
MinimalBy selects all the elements of the original input list with the smallest score according to `IntegerLength`, i.e., with the smallest number of digits; and then Max outputs the largest one.
*Thanks to Martin Ender for finding, and then saving, 2 bytes for me :)*
[Answer]
# [Perl 6](https://perl6.org), 18 bytes
```
*.min:{.chars,-$_}
```
## Explanation:
```
*\        # Whatever lambda
.min:     # find the minimum using
{         # bare block lambda with implicit parameter ｢$_｣
  .chars, # number of characters first ( implicit method call on ｢$_｣ )
  -$_     # then negative of the value in case of a tie
}
```
## Usage:
```
say [738, 2383, 281, 938, 212, 1010].&( *.min:{.chars,-$_} ); # 938
my &code = *.min:{.chars,-$_}
say code [78, 99, 620, 10]; # 99
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~16~~ ~~15~~ 14 bytes
```
|/{=/&/\#'$x}#
```
[Try it online!](https://ngn.codeberg.page/k/#eJxlUNtqwzAMffdXCFp2AY9EVtpYNduPZIHupTA2GJQ9tHTdt+9IbtZ2g/hyLlaks1l9NYfH5qZ5nt3Od8dZCJ+rw3zYf29XGyLalfXHW7lbb15e38uu7Mv2fjzCM0QuPNqpRf3kPmmxzRDTSZaOpIjfMokWcblrlTgRS2HXGP761VdnDMKZPpMqLVM7WS6Itqj+pSaOaUGJ/G9LAZ9qt9ItmJJmeLFDSAmbSF9M8WLoNwmklJnUgDXc2s8kjyE0YeCRHp6Iw6B+UTA2vpO4AEb69UgXSRwIQAaoToEPccCZsKqDYWF7PK2pyBV5YkH3KKcogdEvzNdsW3vUf/xZQNEFpNrKUkxM02QWS6yJ+WEqMoseWh0EjmCxRc8tWnDRkosWXfTsajXJP9wzhD8=)
* `{...}#` set up a filter, returning elements from the (implicit) right argument where the code in `{...}` returns `1`s
	+ `#'$x` count the number of characters in the string representation of each input
	+ `&/\` generate a two item list of the character counts and their minimum
	+ `=/` generate a boolean mask indicating which indices have the fewest digits
* `|/` return the maximum (remaining) value
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes
```
DL€İMị¹Ṁ
```
[Try it online!](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gA&input=&args=WzM0NTEsIDI5ODIwLCAyOTgzLCAxMjIzLCAxMzM3XQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=REzigqzEsE3hu4vCueG5gArDh-KCrA&input=&args=W1sxXSwKIFs5XSwKIFsxNzI5XSwKIFsxLCAxXSwKIFszNCwgM10sCiBbMzgsIDM5XSwKIFs0MDksIDEyLCAxM10sCiBbMTEsIDExLCAxMSwgMV0sCiBbMTEsIDExLCAxMSwgMTFdLAogWzc4LCA5OSwgNjIwLCAxXSwKIFs3OCwgOTksIDYyMCwgMTBdLAogWzc4LCA5OSwgNjIwLCAxMDBdLAogWzEsIDUsIDksIDEyLCA2MywgMTAyXSwKIFszNDUxLCAyOTgyMCwgMjk4MywgMTIyMywgMTMzN10sCiBbNzM4LCAyMzgzLCAyODEsIDkzOCwgMjEyLCAxMDEwXV0)
## Explanation
```
DL€İMị¹Ṁ  Input: list A
D         Convert each integer to a list of base 10 digits
 L€       Get the length of each list (number of digits of each)
   İ      Take the reciprocal of each
    M     Get the indices of the maximal values
      ¹   Get A
     ị    Select the values at those indices from A
       Ṁ  Find the maximum and return
```
[Answer]
# JavaScript (ES6), 51
```
l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]
```
**Test**
```
f=l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]
;[
 [[1], 1]
,[[9], 9]
,[[1729], 1729]
,[[1, 1], 1]
,[[34, 3], 3]
,[[38, 39], 39]
,[[409, 12, 13], 13]
,[[11, 11, 11, 1], 1]
,[[11, 11, 11, 11], 11]
,[[78, 99, 620, 1], 1]
,[[78, 99, 620, 10], 99]
,[[78, 99, 620, 100], 99]
,[[1, 5, 9, 12, 63, 102], 9]
,[[3451, 29820, 2983, 1223, 1337], 3451]
,[[738, 2383, 281, 938, 212, 1010], 938]
].forEach(([l,x])=>{
  var r=f(l)
  console.log(r==x?'OK':'KO',l+' -> '+r)
})
```
[Answer]
# J, ~~21~~ 14 bytes
Saved 7 bytes thanks to miles and (indirectly) Jonathan!
```
{.@/:#@":"0,.-
```
This is a four-chain:
```
{.@/: (#@":"0 ,. -)
```
Let's walk over the input `10 27 232 1000`. The inner fork consists of three tines. `#@":"0` calculates the sizes, `,.` concats each size with its negated (`-`) member. For input `10 27 232 1000`, we are left with this:
```
   (#@":"0 ,. -) 10 27 232 1000
2   _10
2   _27
3  _232
4 _1000
```
Now, we have `{.@/:` as the outer tine. This is monadic first (`{.`) over dyadic sort (`/:`). That is, we'll be taking the first element of the result of dyadic `/:`. This sorts its right argument according to its left argument, which gives us for our input:
```
   (/: #@":"0 ,. -) 10 27 232 1000
27 10 232 1000
```
Then, using `{.` gives us the first element of that list, and we are done:
```
   ({.@/: #@":"0 ,. -) 10 27 232 1000
27
```
## Old version
```
>./@(#~]=<./@])#@":"0
```
Still working on improvements. I golfed it down from 30, and I think this is good enough. I'm going to first break it down into basic parts:
```
   size =: #@":"0
   max =: >./
   min =: <./
   over =: @
   right =: ]
   left =: [
   selectMin =: #~ right = min over right
   f =: max over selectMin size
   f 3 4 5
5
   f 3 4 53
4
   f 343 42 53
53
```
Here's how this works.
```
>./@(#~ ] = <./@]) #@":"0
```
This is a monadic train, but this part is a hook. The verb `>./@(#~ ] = <./@])` is called with left argument as the input to the main chain and the sizes, defined as `#@":"0`, as the right argument. This is computed as length (`#`) over (`@`) default format (`":`), that is, numeric stringification, which is made to apply to the 0-cells (i.e. members) of the input (`"0`).
Let's walk over the example input `409 12 13`.
```
   (#@":"0) 409 12 13
3 2 2
```
Now for the inner verb, `>./@(#~ ] = <./@])`. It looks like `>./@(...)`, which effectively means maximum value (`>./`) of (`@`) what's inside `(...)`. As for the inside, this is a four-train, equivalent to this five-train:
```
[ #~ ] = <./@]
```
`[` refers to the original argument, and `]` refers to the size array; `409 12 13` and `3 2 2` respectively in this example. The right tine, `<./@]`, computes the minimum size, `2` in this case. `] = <./@]` is a boolean array of values equal to the minimum, `0 1 1` in this case. Finally, `[ #~ ...` takes values from the left argument according the right-argument mask. This means that elements that correspond to `0` are dropped and `1` retained. So we are left with `12 13`. Finally, according to the above, the max is taken, giving us the correct result of `13`, and we are done.
[Answer]
# Julia, 39
```
f(l)=sort(l,by=x->(length("$x"),-x))[1]
```
[ATO](https://ato.pxeger.com/run?1=jZBNTsMwEIXFsjlFZCGRSAlK7P7EEolgyYITVCyM6kCQ5Va2C0UqJ2HTTQ9VTsNz3AAVG6Q4mXnvm6dxPvbPa9WJ3eHGiFdCSJuotLZL4xKVPbzVm7xJlNSP7ikh5xuSZvkmTeflPchtE4xtszKddkrv167Nq8PFPyOO-Hu7NLHqdIzHSLFAKW1i3aLTaTQSxmRG2tquVIe8Tmckb0gw6jvpxOVKGCsTtOm2kS9CRSPPB_VWOz8N_FpYK7FR25N13atSL8ISu8-zK2wU501cRnPeFzyalzMaal-gzeJvho2zmPUNQ1OhCSQDNy44SIoTiBJI6YeHM4SciEcV8gxxHBFTWvyCT9Ui7Mj_6D8GQiewwipT5k063IyNJ7Apr_wQPt6l1L8Zm4WLgEC4vxpl3qcVJnjf93crhh1YFYW_-AU)able
[Answer]
# JavaScript (ES6), 62 bytes
```
var solution =
a=>a.map(n=>(l=`${n}`.length)>a?l>a+1|n<r?0:r=n:(a=l-1,r=n))|r
;document.write('<pre>' + `
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
`.split('\n').slice(1, -1).map(c =>
  c + ', result: ' + solution(eval(c.slice(0, c.indexOf('->'))))
).join('\n'))
```
[Answer]
## Javascript (ES6), ~~57~~ ~~54~~ 53 bytes
```
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]
```
For the record, my previous version was more math-oriented but 1 byte bigger:
```
l=>l.sort((a,b)=>(s=a=>1/a-~Math.log10(a))(a)-s(b))[0]
```
### Test cases
```
let f =
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]
console.log(f([1]));                              //  -> 1
console.log(f([9]));                              //  -> 9
console.log(f([1729]));                           //  -> 1729
console.log(f([1, 1]));                           //  -> 1
console.log(f([34, 3]));                          //  -> 3
console.log(f([38, 39]));                         //  -> 39
console.log(f([409, 12, 13]));                    //  -> 13
console.log(f([11, 11, 11, 1]));                  //  -> 1
console.log(f([11, 11, 11, 11]));                 //  -> 11
console.log(f([78, 99, 620, 1]));                 //  -> 1
console.log(f([78, 99, 620, 10]));                //  -> 99
console.log(f([78, 99, 620, 100]));               //  -> 99
console.log(f([1, 5, 9, 12, 63, 102]));           //  -> 9
console.log(f([3451, 29820, 2983, 1223, 1337]));  //  -> 3451
console.log(f([738, 2383, 281, 938, 212, 1010])); //  -> 938
```
[Answer]
## dc, 54 bytes
```
?dZsL0sN[dsNdZsL]su[dlN<u]sU[dZlL=UdZlL>ukz0<R]dsRxlNp
```
**Explanation:**
```
?dZsL0sN                  # read input, initialize L (length) and N (number)
[dsNdZsL]su               # macro (function) 'u' updates the values of L and N
[dlN<u]sU                 # macro 'U' calls 'u' if N < curr_nr
[dZlL=U dZlL>ukz0<R]dsR   # macro 'R' is a loop that calls 'U' if L == curr_nr_len
                          #or 'u' if L > curr_nr_len
xlNp                      # the main: call 'R' and print N at the end
```
**Run example:** 'input.txt' contains all the test cases in the question's statement
```
while read list;do echo "$list -> "$(dc -f program.dc <<< $list);done < input.txt
```
**Output:**
```
1 -> 1
9 -> 9
1729 -> 1729
1 1 -> 1
34 3 -> 3
38 39 -> 39
409 12 13 -> 13
11 11 11 1 -> 1
11 11 11 11 -> 11
78 99 620 1 -> 1
78 99 620 10 -> 99
78 99 620 100 -> 99
1 5 9 12 63 102 -> 9
3451 29820 2983 1223 1337 -> 3451
738 2383 281 938 212 1010 -> 938
```
[Answer]
# Java 7, ~~112~~ 104 bytes
```
int c(int[]a){int i=a[0],j;for(int b:a)i=(j=(i+"").length()-(b+"").length())>0?b:b>i&j==0?b:i;return i;}
```
Different approach to save multiple bytes thanks to *@Barteks2x*.
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/Zo6o2f)
```
class M{
  static int c(int[] a){
    int i = a[0],
        j;
    for(int b : a){
      i = (j = (i+"").length() - (b+"").length()) > 0
           ? b
           : b > i & j == 0
              ? b
              : i;
    }
    return i;
  }
  public static void main(String[] a){
    System.out.println(c(new int[]{ 1 }));
    System.out.println(c(new int[]{ 9 }));
    System.out.println(c(new int[]{ 1729 }));
    System.out.println(c(new int[]{ 1, 1 }));
    System.out.println(c(new int[]{ 34, 3 }));
    System.out.println(c(new int[]{ 409, 12, 13 }));
    System.out.println(c(new int[]{ 11, 11, 11, 1 }));
    System.out.println(c(new int[]{ 11, 11, 11, 11 }));
    System.out.println(c(new int[]{ 78, 99, 620, 1 }));
    System.out.println(c(new int[]{ 78, 99, 620, 100 }));
    System.out.println(c(new int[]{ 1, 5, 9, 12, 63, 102 }));
    System.out.println(c(new int[]{ 3451, 29820, 2983, 1223, 1337 }));
    System.out.println(c(new int[]{ 738, 2383, 281, 938, 212, 1010 }));
  }
}
```
**Output:**
```
1
9
1729
1
3
13
1
11
1
99
9
3451
938
```
[Answer]
# bash, awk, sort 53 bytes
```
set `awk '{print $0,length($0)}'|sort -rnk2n`;echo $1
```
Read input from stdin, one value per line
# bash and sort, ~~58~~ 57 bytes
```
set `sort -n`;while((${#2}==${#1}));do shift;done;echo $1
```
[Answer]
# JavaScript ES6, ~~80~~ ~~77~~ 70 bytes
```
a=>Math.max(...a.filter(l=>l.length==Math.min(...a.map(i=>i.length))))
```
I hope I am going in the right direction...
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 16 bytes
```
or:@]feL:la#=,Lh
```
[Try it online!](http://brachylog.tryitonline.net/#code=b3I6QF1mZUw6bGEjPSxMaA&input=WzM0NTE6Mjk4MjA6Mjk4MzoxMjIzOjEzMzdd&args=Wg)
### Explanation
```
or                 Sort the list in descending order.
  :@]f             Find all suffixes of the list.
      eL           Take one suffix L of the list.
        :la        Apply length to all numbers in that suffix.
           #=,     All lengths must be equal.
              Lh   Output is the first element of L.
```
[Answer]
# Haskell, 39 bytes
```
snd.maximum.map((0-).length.show>>=(,))
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 11 bytes
```
tV48\&XS0))
```
Input is a column vector (using `;` as separator), such as
```
[78; 99; 620; 100]
```
[Try it online!](http://matl.tryitonline.net/#code=dFY0OFwmWFMwKSk&input=WzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0VjQ4XCZYUzApKQpEVA&input=WzFdCls5XQpbMTcyOV0KWzE7IDFdClszNDsgM10KWzM4OyAzOV0KWzQwOTsgMTI7IDEzXQpbMTE7IDExOyAxMTsgMV0KWzExOyAxMTsgMTE7IDExXQpbNzg7IDk5OyA2MjA7IDFdCls3ODsgOTk7IDYyMDsgMTBdCls3ODsgOTk7IDYyMDsgMTAwXQpbMTsgNTsgOTsgMTI7IDYzOyAxMDJdClszNDUxOyAyOTgyMDsgMjk4MzsgMTIyMzsgMTMzN10KWzczODsgMjM4MzsgMjgxOyA5Mzg7IDIxMjsgMTAxMF0).
### Explanation
Let's use input `[78; 99; 620; 100]` as an example.
```
t      % Input column vector implicitly. Duplicate
       %   STACK: [78; 99; 620; 100], [78; 99; 620; 100]
V      % Convert to string. Each number is a row, left-padded with spaces
       %   STACK: [78; 99; 620; 100], [' 78'; ' 99'; '620'; '100']
48\    % Modulo 48. This transforms each digit into the corresponding number,
       % and space into 32. Thus space becomes the largest "digit"
       %   STACK: [78; 99; 620; 100], [32 7 8; 32 9 9; 6 2 0; 1 0 0]
&XS    % Sort rows in lexicographical order, and push the indices of the sorting
       %   STACK: [78; 99; 620; 100], [4; 3; 1; 2]
0)     % Get last value
       %   STACK: [78; 99; 620; 100], 2
)      % Index
       %   STACK: 99
       % Implicitly display
```
[Answer]
# Perl, ~~38~~ 37 bytes
Includes +1 for `-a`
Give input on STDIN:
```
perl -M5.010 maxmin.pl <<< "3451 29820 2983 1223 1337"
```
`maxmin.pl`:
```
#!/usr/bin/perl -a
\$G[99-y///c][$_]for@F;say$#{$G[-1]}
```
Uses memory linear in the largest number, so don't try this on too large numbers. A solution without that flaw is 38 bytes:
```
#!/usr/bin/perl -p
$.++until$\=(sort/\b\S{$.}\b/g)[-1]}{
```
All of these are very awkward and don't feel optimal at all...
[Answer]
## PowerShell v2+, 41 bytes
```
($args[0]|sort -des|sort{"$_".length})[0]
```
Takes input `$args`, `sort`s it by value in `-des`cending order (so bigger numbers are first), then `sort`s that by the `.length` in ascending order (so shorter lengths are first). We then take the `[0]` element, which will be the biggest number with the fewest digits.
## Examples
```
PS C:\Tools\Scripts\golfing> @(78,99,620,1),@(78,99,620,10),@(78,99,620,100),@(1,5,9,12,63,102),@(3451,29820,2983,1223,1337),@(738,2383,281,938,212,1010)|%{($_-join',')+" -> "+(.\output-largest-number-fewest-digits.ps1 $_)}
78,99,620,1 -> 1
78,99,620,10 -> 99
78,99,620,100 -> 99
1,5,9,12,63,102 -> 9
3451,29820,2983,1223,1337 -> 3451
738,2383,281,938,212,1010 -> 938
```
[Answer]
# R, ~~72~~ ~~41~~ 36 bytes
Rewrote the function with a new approach. Golfed 5 bytes thanks to a suggestion from @bouncyball.
```
n=nchar(i<-scan());max(i[n==min(n)])
```
Explained:
```
        i<-scan()       # Read input from stdin
n=nchar(         );     # Count the number of characters in each number in i
max(             )      # Return the maximum of the set where
    i[n==min(n)]        # the number of characters is the minimum number of characters.
```
```
function(i){while(1){if(length(o<-i[nchar(i)==T]))return(max(o));T=T+1}}
```
Indented/explained:
```
function(i){               # Take an input i
  while(1){                # Do the following continuously:
    if(length(
        o<-i[nchar(i)==T]) # Define o to be the subset of i with numbers of length T,
      )                    # where T is 1 (a built-in!).
                           # We take the length of this subset (its size), and then pass
                           # it to if(). Thanks to weak typing, this numeric is converted
                           # to a logical value. When this occurs, zero evaluates to FALSE
                           # and any non-zero number evaluates to TRUE. Therefore, the if()
                           # is TRUE iff the subset is not empty.
      return(max(o));      # If it's true, then we just return the largest element of the
                           # subset, breaking out of our loop.
    T=T+1                  # Otherwise, increment our counter and continue.
  }
}
```
[Answer]
## Bash + coreutils, 58 bytes
```
d=`sort -n`;egrep ^.{`sed q<<<"$d"|wc -L`}$<<<"$d"|tail -1
```
Input format is one value per line. Golfing suggestions are welcomed.
**Explanation:**
```
d=`sort -n`                             #save the list in ascending numerical order
egrep ^.{                    }$<<<"$d"  #print only list lines having as many chars
         `sed q<<<"$d"|wc -L`                 #as the first sorted line does
|tail -1                                #and then get the last one (the answer)
```
[Answer]
# **Python 2 - 41 bytes**
```
lambda l:max((-len(`x`),x) for x in l)[1]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 bytes
-4 thanks to @rak1507.
```
f←⌈/⊢×((⌊/=⊢)≢∘⍕¨)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPR36j7oWHZ6uofGop0vfFsjWfNS56FHHjEe9Uw@t0Pz/qG8qUFmagrmxhY6CkbGFMZC0MNRRsATzDY10FAwNDA24YMqAMqZASaAoUMbMGCRr9B8A "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
DL$ÐṂṀ
```
[Try it online!](https://tio.run/##ZU8rDsJAEPU9xQpkSboz/a1BERSahDSVGNIL4JoaEhQXwIBFItoge5LtRZa3XRZoELM77zMvM/tdVR2MWa5n/Vl3je5qo9uT7m5DfSl1e92s@mOgn4/@ODT3rTGFLMV8IWRQqLFRQSEzcr1tAEPx8XAcCh4BA@QAzsnwxZGCk1DOIWGRdtiXD5mQbxZ0hjiFiJSiH/OUjdyO6o//CghNILlVUrYi@cs4TiCTyu0QPqsS2Zc5c4fAgXB7GrHVKceEGvF4W@R34PwF "Jelly – Try It Online")
## How it works
```
DL$ÐṂṀ - Main link. Takes a list L on the left
  $ÐṂ  - Take the elements of L for which the following is minimal:
DL     -   Digit Length
     Ṁ - Maximum of those elements
```
]


[Question]
      []