title: 'abc' and 'cba'

text:
# Question
Title: 'abc' and 'cba'
Your task is simple, write a single code snippet that when executed in one language outputs only the string `'abc'` and when executed in another language outputs only the string `'cba'`. The program should take no input.

This is a challenge.

# Answer
> 23 votes
# MATLAB / Octave, 41 bytes

```
disp(flip('abc',size(randsample(2,2),2)))

```

In MATLAB `randsample(2,2)` gives a 2×1 vector, so `size(...,2)` is `1`. Thus `flip` is applied along the first dimension, which is a singleton, so the original string `'abc'` is displayed:

In Octave `randsample(2,2)` gives a 1×2 vector, so `size(...,2)` is `2`. Thus `flip` is applied along the second dimension, that is, the string is flipped from left to right:

# Answer
> 21 votes
# 05AB1E / Pyth, 5 bytes

```
_"abc

```

**Try 05AB1E online!**

**Try Pyth online!**

**This also works in Pyke, outputting `cba`.**

**This also works in Recursiva, outputting `cba`.**

# Answer
> 16 votes
# Whitespace and Bash, 57 bytes

```

echo  cba

```

Try it online!

# Answer
> 15 votes
# 25 bytes

```
print(1/2and'cba'or'abc')

```

Try it online! (Python 2)

Try it online! (Python 3)

# Answer
> 12 votes
# Vim / Notepad.exe, 10 bytes

```
cbaabc<esc><backspace><backspace><backspace>

```

# Answer
> 11 votes
-1 byte if I make `==0` into `>0` but that's already another answer

# Python 2, 26 bytes

```
print('acbbca'[1/2==0::2])

```

Try it online!

---

# Python 3, 26 bytes

```
print('acbbca'[1/2==0::2])

```

Try it online!

`1/2` gives `0` (floordiv) in Python 2 and `0.5` (truediv) in Python 3. Thus, `1/2==0` gives 1 in Python 3 and 0 in Python 2 (actually, booleans, but those are just integers), so `'acbbca'[1::2] => 'cba'` is given for Python 3 and `'acbbca'[0::2] => 'abc'` is given for Python 2.

# Answer
> 11 votes
# Excel / Google Sheets, ~~41~~ ~~28~~ ~~27~~ 24 Bytes

Anonymous worksheet formula that takes no input and outputs `"ABC"` to the calling cell in Excel and `"CBA"` to the calling cell in Google Sheets

```
=IfError(M("CBA"),"ABC")

```

In Google Sheets, `M(...)` is an alias for and autoformatted to `T(...)` (short for `Text()`). This call returns the text value of the passed variable, `"CBA"`. `"CBA"` is not caught as an error, so `"CBA"` is returned by `IfError(...,"ABC")`

In Excel, there is no `M(...)` function, and `M(...)` is not an alias and therefore `M("CBA")` returns the formula not found error, `#NAME?`. This is caught by `IfError(...,"ABC")`, which in turn returns `"ABC"`.

---

## Previous Versions, 27, 28, 41 Bytes

See edits for explanations

```
=If(IsErr(A()),"ABC","CBA")

```

```
=If(IsErr(GT()),"ABC","CBA")

```

```
=IfError(If(Info("NUMFILE"),"ABC"),"CBA")

```

# Answer
> 9 votes
# CJam / 05AB1E, 6 bytes

```
"abc"R

```

Try it online:

### How it works in CJam

```
"abc"    Push this string
R        Push variable R, predefined to the empty string
         Implicitly display stack

```

### How it works in 05AB1E

```
"abc"    Push this string
R        Reverse
         Implicitly display top of the stack

```

# Answer
> 8 votes
With apologies to @HyperNeutrino for stealing most of his answer (I don't have the reputation to comment yet)

# Python 2, 25 bytes

```
print('acbbca'[1/2>0::2])

```

Try it online!

# Python 3, 25 bytes

```
print('acbbca'[1/2>0::2])

```

Try it online!

# Answer
> 7 votes
# JavaScript (NodeJS) and PHP, 46 bytes

```
<!--
strrev=console.log//--><?=
strrev("abc");

```

Prints `abc` in JS and `cba` in PHP.

Try the JS online!

Try the PHP online! (note that TIO doesn't hide the HTML comments (`<!--`...`-->`)

# Answer
> 6 votes
# Python 2 and Python 3, 42 bytes

```
try:exec("print'abc'")
except:print('cba')

```

Try it online! (Python 2)

Try it online! (Python 3)

Thought I'd try something different...

# Answer
> 6 votes
# Python / Befunge, ~~20~~ 18 bytes

*2 bytes saved thanks to @karhell*

```
print("abc")# ,,,@

```

Try it online! for Python

Python sees `print("abc")` then a comment.

Try it online! for Befunge

Befunge, removing all nops and useless commands sees `"abc",,,@` which puts `a`, `b` and `c` on the stack and then prints them (last in - first out).

# Answer
> 6 votes
# Excel/Google Sheets, 28 bytes

Inspired by @TaylorScott, who used a function that only exists in Excel, I found an even shorter function that only exists in Google Sheets. Conveniently, it is designed to return strings:

```
=iferror(join(,"cba"),"abc")

```

**How it works**

In Google Sheets, `join([arg1], arg2, arg3,...argk)` will concatenate *arg2* -\> *argk*, optionally using the separator specified in *arg1*. In this case, it successfully returns "cba."

Excel has no `join` function, so `iferror` sees a problem and returns "abc"

# Answer
> 5 votes
# Python 2 / Python 3, 28 bytes

```
print('abc'[::int(1/2*4)-1])

```

In Python 2 `int(1/2*4)-1` evaluates to `-1` and so prints `cba`. - TiO

In Python 3 it evaluates `1` so prints `abc`. - TiO

# Answer
> 5 votes
# /Cubix, 20 bytes

```
cat("abc")#u@o;o;o(;

```

R - Try it online!

Cubix - Try it online!

For R, `cat("abc")` then shameless abuse of comments. For Cubix

```
    c a
    t (
" a b c " ) # u
@ o ; o ; o ( ;
    . .
    . .

```
* `"abc"` Pushs a, b ad c onto the stack
* `)#` Increment the c, pushs number of element in stack
* `u` U-turn to the right
* `;(` Remove the count, Decrement the c
* `o;o;o@` Output cba and exit

Pushs the number on in stack

# Answer
> 4 votes
# C and C++, ~~115~~, ~~78~~, ~~58~~, 56 bytes

```
#include<stdio.h>
main(){puts(sizeof('x')>1?"abc":"cba");}

```

78 bytes, thanks to challenger5.

58 bytes, thanks to aschepler.

56 bytes, thanks to hvd

Try it - C++!

Try it - C!

# Answer
> 4 votes
# CJam and Gaia, 8 bytes

```
'c'b'a]$

```

Try it in CJam!

Try it in Gaia!

### Explanation

In both languages this defines a list of characters.

In CJam, `$` is sort, so it becomes `abc`.

In Gaia, `$` joins the list into one string, giving `cba`.

# Answer
> 4 votes
# Java 8 & C, 95 bytes

```
//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

```

Try it in Java 8 - resulting in "abc".
Try it in C - resulting in "cba".

**Explanation:**

```
//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

```

As you can see in the Java-highlighted code above, the first line is a comment due to `//`, and the C-code is a comment due to `/* ... */`, resulting in:

```
interface a{static void main(String[]s){System.out.print("abc");}}

```

---

```
//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

```

Not sure how to correctly enable C-highlighting, because `lang-c` results in the same highlighting as Java.. But `//\` will comment out the next line, which is the Java-code, resulting in:

```
main(){{puts("cba");}}

```

# Answer
> 4 votes
# Japt 2.0/JavaScript, ~~11~~ 10 bytes

```
"abc"
//Uw

```

Japt 2.0 outputs `cba`

JavaScript outputs `abc`

# Answer
> 4 votes
# Vyxal/Hexagony, 19 bytes

```
ka3wiṘ,Qλa;b@;<λ;c/

```

Try it Online! (Vyxal)

Try it Online! (Hexagony)

The program is split into two main parts, `ka3wiṘ,Q` and `λa;b@;<λ;c/`. The first half is just basic Vyxal to print "cba" (though I cannot use \`cba\` because it messes with Hexagony's layout). The second part worked out really nicely, because in order to print in Hexagony, a semicolon is required, but in Vyxal, an unmatched semicolon gives an error. So to fix this, I use lambdas in order to match them, and it just so happened to fit into an exact 3x3 hexagon. Luckily, in Hexagony almost any character that isn't special is taken as its codepoint, so the lambda character is quickly overwritten by anything else that comes after it.

The lambdas are placed so each one proceeds a semicolon, even if they aren't used in the hexagony code (as indicated by the blue trail).

# Answer
> 3 votes
# Python 3, 26 bytes

```
print('abc'[::-(1/2>0)|1])

```

Try it online!

# Python 2, 26 bytes

```
print('abc'[::-(1/2>0)|1])

```

Try it online!

25-byte version with `exit` instead, which outputs to STDERR instead.

This is basically the same as `print('abc'[::[1,-1][1/2>0]])`, just that it's golfed.

# Answer
> 3 votes
# Ly / \>\<\>, ~~20~~ 19 bytes

```
"abc"&&ov
;     oo<

```

Try it with \>\<\>!

Try it with Ly!

These languages are very similar, as Ly is based off \>\<\>. However, Ly does not have 2D execution and interprets `&` differently, which I took advantage of here.

Both languages will start by pushing `abc` to the stack.

For \>\<\>, the `&` instruction moves values to and fro the register. Two in a row will push a value to the register and then take it straight back, essentially a NOP.

For Ly, `&` is a modifier that makes an instruction perform its function on the entire stack.

`o` means the same thing for both languages, but since it is modified by `&` in Ly, it will print the whole stack, outputting `abc`. In \>\<\>, it will only output `c` (as it is printed from the top down)

`v` is a NOP in Ly, which skips it and goes straight to `;`, ending execution. \>\<\> will instead treat it as a pointer, sending the IP downwards.

It then hits another arrow, sending the IP left. Here, it meets two `o` signs, outputting `b` and `a`.

EDIT: Saved a byte (and fixed \>\<\> crashing)

# Answer
> 3 votes
# CJam and \>\<\>, 12 bytes

```
"ooo;abc
"4>

```

## What CJam sees:

```
"ooo;abc
"

```

String literal, which pushes the string `ooo;abc` (with a trailing newline) to the stack.

```
 4>

```

Slice off the first four characters of the string, leaving `abc`, which is output.

## What \>\<\> sees:

```
"

```

Begins a string literal.

```
 ooo;abc

```

Forms the contents of the string literal. The character codes of the characters in the string are pushed to the stack in reverse order (so `c` is on the top).

```
"

```

The IP wraps around, hitting the `"` a second time, which ends the string literal.

```
 ooo

```

Outputs the top three characters on the stack: `cba`

```
    ;

```

Terminates the program. Neither the `abc` nor any part of the second line is executed.

## Solution with Error: 8 bytes

```
"abc"oo<

```

What CJam sees (Try it online!):

```
"abc"

```

Push a string literal to the stack.

```
    o

```

Output that string literal.

```
     o

```

Try to output again. The stack is empty, so the program crashes.

## What \>\<\> sees:

```
"abc"

```

Push three characters onto the stack in reverse order.

```
    o

```

Print one character: `c`

```
     o

```

Print another character: `b`

```
      <

```

Start moving backwards.

```
     o

```

Print the last character: `a`

```
    o

```

Try to print another character. Since the stack is empty, the program errors.

# Answer
> 3 votes
# Python 2 and Foo, 16 bytes

```
print"abc"[::-1]

```

## Python 2

```
print"abc"[::-1]

```

Try Python 2 online!

### Explanation

```
print"abc"[::-1]

print             # print... (duh)
     "abc"        # the string "abc"...
          [::-1]  # backwards

```

## Foo

```
"abc"

```

Try Foo online!

### Explanation

```
"abc"

"abc"               print the string "abc"

```

# Answer
> 3 votes
# C (gcc) C++ (g++), 59 bytes

```
#include<stdio.h>
main(){puts("abc\0cba"+(sizeof(' ')&4));}

```

# Answer
> 3 votes
# Fission / \>\<\> , 11 bytes

```
!R"abc"ooo;

```

Try Fission Online

In Fission, a particle starts at `R` and prints `abc`.

Try \>\<\> Online

In \>\<\>, the IP starts at the top-left. `!` skips the next instruction, and `"abc"` pushes \[a,b,c\] on the stack. `ooo` then pops and prints three times, giving `cba`.

Both programs end at `;`

# Answer
> 3 votes
## Javascript / Ruby, 27 bytes

```
0?print('abc'):alert('cba')

```

A shorter version without prints for interpreters (**14 bytes**) :

```
0?'abc':'cba'

```

\**Explanation\**

*NEW VERSION* `0` is falsy for Javascript but truthy for Ruby, thanks to pxeger

*OLD VERSION*: `''` is falsy for Javascript, but truthy for Ruby.

*OLD VERSION*: For Javascript, `[]+[] = ""` as a string concatenation, since the `+` operand is only defined for numbers and strings, and the empty string is evaluated as `false`

Meanwhile, in Ruby, you can concatenate array using the `+` operand, and it is evaluated as `true`

(first participation in PCG ! :))

# Answer
> 3 votes
# /K (Kona), 30 bytes

```
NB. :`0:"ABC"
{}[] /.echo'CBA'

```

TIO - J & TIO - K kona

# Answer
> 3 votes
# Julia and Python 3, 23 bytes

```
print(["abc","cba"][1])

```

Try Julia online!

Try Python online!

Julia uses 1-based indexing while Python uses 0-based indexing

# Answer
> 2 votes
# 05AB1E and 2sable, 6 bytes

```
…CBAžR

```

Prints `ABC` (OP said it was allowed) in 05AB1E and `CBA` in 2sable, using the fact that 2sable was similar to 05AB1E but the `žR` was added to 05AB1E after 2sable was abandoned.

Try it online! (05AB1E)

Try it online! (2sable)

# Answer
> 2 votes
# PHP + JavaScript, ~~29~~ 28 bytes

This works because PHP interprets `'0'` (same as the integer number `0`) as being falsy, while JavaScript assumes it is simply a non-empty string which is truthy.

```
'0'?alert('cba'):print(abc);
```

This is meant to run with `-r` on PHP. In Javascript, just paste it in the console.

---

Thanks to @Justin Mariner for saving me 1 byte!

# Answer
> 2 votes
# Braingolf and Lean Mean Bean Machine, 35 bytes

```
 O
""
#a
!!
""
#b
!!
""
#c
& ,&
@U;

```

Braingolf: Try it online!
LMBM: Try it online!

Outputs `abc` in LMBM, and `cba` in Braingolf.

## Explanation

LMBM is a 2d language, which allows us to selectively execute the code we want.
Meanwhile Braingolf is a 1d language, meaning it starts at the top left, and goes across each line, executing code. It terminates upon reaching the end of the code.

In LMBM, a marble is spawned at every uppercase `O` when the program starts. Each tick it drops 1 character and executes the character. LMBM terminates once all marbles are destroyed.

A double quote `"` in LMBM sets the marble to char mode, meaning the next character to execute is interpreted as a 1 char string literal, and the marble's value is set to the codepoint of the character.

However `"` begins and terminates a string in Braingolf, automatically pushing the contents to the stack. Thankfully an empty string does nothing.

`!` in LMBM prints the marble's value as a char, however this is the silent modifier in Braingolf. Thankfully in braingolf v1, modifiers are only held through no-ops, meaning they will be dropped when braingolf hits the empty string, which doesn't use modifiers (unlike v2 where they are held until used) so we don't have to make sure to consume that modifier before we try to print the stack.

In Braingolf `#` is the char literal identifier, causing the codepoint of the next char to be pushed to the stack.

After passing through all of the characters (and in LMBM's case printing the first 2) we hit the last 2 lines.
The 2nd to last line does nothing in LMBM, as it simply drops through the space, a no-op.

In Braingolf however, the ampersand `&` is the greedy modifier. Modifiers in Braingolf are held through no-ops such as the space, until an operator consumes them, so the first ampersand is held through the space until it hits the comma `,` Braingolf's flip operator. The greedy modifier is consumed here to cause Braingolf to flip the entire stack, rather than the top 2 items. Then another greedy modifier is hit.
This one is held through the newline to the at `@` sign, this prints the entire stack as ASCII.

Meanwhile LMBM simply drops through the space into the `U`, which prints the marble's value as ASCII and destroys the marble.
The `U` also has a function in Braingolf, it pops the top of the stack and pushes `range(0...n)`, but the stack is empty because we just popped and printed everything, so this does nothing.

# Answer
> 2 votes
# PHP / Brainf\*ck, 31 bytes

*using the `-r` flag,*

PHP sees `die(abc)` and a comment, and since the compiler is forgiving, it outputs `abc` as a string instead of an empty variable.

Brainf\*ck only sees the instruction characters, and the rest is seen as comments.

```
die(abc);#--[----->+<]>---.-.-.

```

Try it online! (PHP)

Try it online! (Brainf\*ck)

# Answer
> 2 votes
# C / Common Lisp, ~~91~~ ~~88~~ ~~40~~ 36 bytes

```
//(princ"abc")
;main(){puts("cba");}

```

Try it online – C

Try it online – Common Lisp

Both “normal” languages with very different syntax and semantics!

**Explanation**

For Common Lisp:

`//` is a special variable used in the Common Lisp REPL to give the result of the value preceding the previous one, initially equal to `NIL`. Then we prints `abc`. The following line starts with a semicolon, which is used to start one-line comments.

For C:

the first line is a comment, and the other is the program. Note that the semicolon before the definition of the `main` function is syntactically correct.

*-1 byte thanks to @Zacharý*

# Answer
> 2 votes
## Julia and Octave/Matlab, 27 bytes

```
if'a'=="a""abc"else"cba"end

```

In Octave, both `'a'` and `"a"` represent the same string, therefore `'a'=="a"` is true. However, in Julia, `'a'` is a single character while `"a"` is a one-character string. In Julia, `"cba"` is the output.

Ungolfed version:

```
if 'a'=="a"
  "abc"
else
  "cba"
end

```

# Answer
> 2 votes
## Perl / Ruby, 18 bytes

### Ruby

```
print'abc'.reverse

```

`print`s `cba` as we're calling `.reverse` on the string.

Try it online!

### Perl

```
print'abc'.reverse

```

`print`s `abc` concatenated with the result of `reverse` which by default works on `$_` which is empty and so makes no difference.

Try it online!

# Answer
> 2 votes
# Python and Ruby, 30 bytes

```
print(['abc','cba'][(0 or 1)])

```

Ruby: the logical `or` short-circuits on 0, which is a truthy value.

Python: 0 is false, and the logical `or` yields 1.

# Answer
> 2 votes
# Japt/Japt 2.0, 14 bytes

```
;AÊ?"abc":"cba

```

Japt outputs `cba`

Japt 2.0 outputs `abc`

# Answer
> 2 votes
# MAWP / 1+, 71 bytes

```
1%(|"+1%+)1%()"+"+"+()();1%()"+"+"+()"+;1%()"+"+"+"+();77W2W1A!!;1M;2M;

```

Uses the % operator to remove all the stray 1's from the 1+ program. Rounded brackets are immediately skipped since there is no 0 in the stack for MAWP.

Try it! (MAWP)

Try it Online! (1+)

# Answer
> 2 votes
# Ruby / C, ~~26~~ 20 bytes

```
puts(0?"abc":"cba");

```

-6 from Dom Hastings.

Try it online! (Ruby)

Try it online! (C)

0 is a truthy value in Ruby, so it prints "abc", and C prints "cba".

`puts` is a function that works in both languages.

# Answer
> 2 votes
# JavaScript (V8), 65 bytes

```
console.log(parseInt('abc--[----->+<]>---.-.-.',16).toString(16))

```

Try it online!

# brainfuck, 65 bytes

```
console.log(parseInt('abc--[----->+<]>---.-.-.',16).toString(16))

```

Try it online!

# Answer
> 1 votes
# Python 2, 27 bytes

```
print(['abc','cba'][1/2>0])

```

Try it online!

# Python 3, 27 bytes

```
print(['abc','cba'][1/2>0])

```

Try it online!

# Answer
> 1 votes
# Python 2 and Python 3, 31 bytes

```
print(round(.5)and"abc"or"cba")

```

Uses the `and`/`or` trick from Erik the Outgolfer's answer, as well as the fact that Python 3 uses banker's rounding, while Python 2 does not.

Try it - Python 2!

Try it - Python 3!

# Answer
> 1 votes
# Python 2, 28 bytes

```
print("abc"[::1/2and-1or 1])

```

Try it online!

# Python 3, 28 bytes

```
print("abc"[::1/2and-1or 1])

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES8 & ES6), 24 bytes

```
_=>"".padEnd?"abc":"cba"

```

# Answer
> 1 votes
# 05AB1E and MY, 22 bytes

Try it online! (05AB1E)

Hex String in Python:

```
'"abc"?\x8e\x01\x06\x89(\x02\x06\x89(\x80\x03\x06\x89(\x80&'

```

Rendered in 05AB1E's codepage:

```
"abc"?Žʒε‰(αε‰(€βε‰(€&

```

Rendered in MY's unimplemented codepage:

```
_RrH_⌈≡16ǵ'26ǵ'+36ǵ'+←

```

### How?

Here is what 05AB1E sees:

```
"abc"?Žʒε‰(αε‰(€βε‰(€&
"abc"                   -  The string "abc"
     ?                  -  Print (no newline)
      Ž                 -  Break on empty stack
       ʒε‰(αε‰(€βε‰(€&  - Unread junk

```

What MY sees (I added a feature which causes errors to produce `0`, in addition to fixing the `r` command.):

```
_RrH_⌈≡16ǵ'26ǵ'+36ǵ'+←
_                       Negate (0)
 R                      Convert to binary ([0])
  r                     Convert from binary (0)
   H                    Convert to hex ("0")
    _                   Negate (errors, so 0)
     ⌈                  Ceiling (0)
      ≡                 Match (0 0=>1)
       16ǵ'             'a'
           26ǵ'+        Prepend 'b'
                36ǵ'+   Prepend 'c'
                     ←  Output without a newline

```

I could have used , but I don't want to divide by 0 to result in 0.

(Use the file `polyglot.py`)

# Answer
> 1 votes
# C/\>\<\>, 58 bytes

```
#include <stdio.h>//^
int main(){puts(/*/*/"abc"//ooo;
);}

```

# Answer
> 1 votes
# /Vim, 6 bytes

```
iabcæ

```

Try it online!

V: `cba`

Vim: `abc`

V and Vim are backwards compatible, but V has many more commands mapped. In V, `æ` means `<M-f>lip` where it's meaningless in Vim.

# Answer
> 1 votes
# JavaScript / Pascal, 40 bytes

**JavaScript**

Outputs "abc".

```
{alert`abc`/*}begin write('cba')end.{*/}
```

---

**Pascal**

Outputs "cba".

```
{alert`abc`/*}begin write('cba')end.{*/}

```

Try it online!

---

Pascal conveniently uses `{ }` for block comments and, in JavaScript, `{ }` are just scopes, which affect nothing in this context.

# Answer
> 1 votes
## C and x86 DOS binary, 58 bytes

```
/* VX4!PZSXNN4s(D (D"5s@SCYAAA@!6cba*/main(){puts("abc");}

```

# Answer
> 1 votes
## Pyth / Canvas, 14... bytes?

```
<4"abcｊｊｊ±" \┐

```

Try it in Pyth!
Try it in Canvas!

---

### Pyth explanation:

```
<4                # All but the last 4 characters of:
  "abcｊｊｊ±"   　# String literal
               \┐ # Char literal, printing suppressed

```
Python 3 translation:
```
print("abcｊｊｊ±"[:-4])
"┐"

```

---

### Canvas explanation:

```
Code               | Explanation                         | Stack
-------------------+-------------------------------------+----------------
<4"abc             | Push "<4\"abc" to the stack         | "<4\"abc"
      ｊｊｊ        |Remove first three characters of ToS | "abc"
           ±       | Reverse ToS                         | "cba"
             " \   | Push "\" \\" to stack               | "cba", "\" \\"
                 ┐ | Remove ToS                          | "cba"
                   | Print ToS (implicit)                |

```

# Answer
> 1 votes
# brainfuck / Jelly, 24 bytes

```
-[+[>+<<]>+]>+.+.+.
“CBA

```

is encoded as `0xFE` in Jelly's codepage. Jelly's codepage is backwards compatible with printable ASCII, so all other characters are encoded the same.

## To brainfuck

Try it online!

`-[+[>+<<]>+]>` sets a cell to 64. `+.+.+.` increments and outputs three times, printing `ABC`.

## To Jelly

Try it online!

The first line is parsed as valid Jelly, but is ignored.

The second line is a string literal with content `CBA`. The last line of the file is the main link, so this is printed.

# Answer
> 1 votes
# Swift / JavaScript, 34 bytes

```
/*/*/alert`cba`// */*/print("abc")

```

Try it Online! (Swift)

Testing snippet (JavaScript):

```
/*/*/alert`cba`// */*/print("abc")
```

This works by abusing nested block comments in Swift. Swift interprets the code as `/*/* Comment */*/print("abc")` while JavaScript interprets the code as `/*Comment*/alert`cba`//Comment`

# Answer
> 1 votes
# Python 3 and Batch, 24 bytes

```
print('abc')#|echo cba

```

This program just takes advantage of operators in both languages.

**What Python Sees**

`print('abc') # This is a comment, do not run`

**What Batch Sees**

`oh noes! errors! run this -> echo cba`

# Answer
> 1 votes
# Tcl, 79 bytes

```
#include<stdio.h>/*
proc M {} {puts cba}
#*/
#define M main(){printf("abc");}
M

```

Try it online!

---

# C (gcc), 79 bytes

```
#include<stdio.h>/*
proc M {} {puts cba}
#*/
#define M main(){printf("abc");}
M

```

Try it online!

# Answer
> 1 votes
# Pxem (ぬこ's intended specification) and Pxem (pxemi.7z: his actual implementation), 16 bytes.

Filename:

```
.wcba.p.d.aabc.p

```

Content is empty.

## What it does

ぬこ, the designer of Pxem, originally intended that `.w` should NOT get into the loop when stack is empty, but his reference implementation does not satisfy it: it gets into the loop when stack is empty. This is why none of we, implementers, have ever complied his intended specification at all.

# Answer
> 0 votes
## JScript, VBScript, 42 bytes

```
rem=1;a="abc"/*
a="cba"'*/
WScript.echo(a)
```

# Answer
> 0 votes
# C / \>\<\>, 33 bytes

```
#//;ooo"cba"
main(){puts("abc");}

```

## What C sees

Try it online!

```
#

```

Begin empty preprocessor directive.

```
//;ooo"cba"

```

Single-line comment.

```

main(){puts("abc");}
```

Print `abc`.

## What \>\<\> sees

Try it online!

```
#

```
Reflect the code in the other direction.
```
       "cba"

```

String literal. Push the character codes of `abc` to the stack in order.

```
    ooo

```

Output each of those characters. Since `c` is at the top of the stack, it is output first.

```
   ;

```

End the program.

```
 //
main(){puts("abc");}

```

Never executed.

# Answer
> 0 votes
# \>\<\> and Underload, 14 bytes

```
"(abc)S"}}ooo;

```

## To \>\<\>:

Try it online!

```
"(abc)S"

```

String literal. Push the character codes of `(abc)S` to the stack.

```
        }}

```

Move the TOS to the bottom twice.

```
          ooo

```

Output three characters (`cba`).

```
             ;

```

Halt.

## To Underload:

https://tio.run/##K81LSS3KyU9M@f9fSSMxKVkzWKm2Nj8/3/r/fwA

```
"

```

Unrecognized

```
 (abc)

```

Push the string `abc`.

```
      S

```

Output it.

```
       "}}ooo;

```

More unrecognized characters.

# Answer
> 0 votes
# Javascript and Japt, ~~18~~ 15 bytes

```
$Pw=P="cba";$Pw

```

Outputs `"abc"` in Japt and `"cba"` Javascript.

Try it online!

# Answer
> 0 votes
# Add++/Whispers v2, 29 bytes

```
x:"abc"
O
> "cba"
>> Output 1

```

**Try Add++ online!**

**Try Whispers online!**

This exits with an exit code of **1** when run in Add++.

## How it works

### Add++

Add++ goes through each line in a linear fashion, executing as it does so. The first line

```
x:"abc"

```

sets the **`x`** variable to the string `abc`. Then

```
O

```

outputs that string. Next

```
> "cba"
>> Output 1

```

(the Whispers code), compares the strings `abc` and `cba` lexicographically before throwing an error at the double `>>` on the fourth line.

### Whispers

Whispers removes any lines which don't match one of it's five regexes, all of which only match lines beginning with `>`, making the code processed by Whispers

```
> "cba"
>> Output 1

```

Whispers' execution model is almost the exact opposite of Add++; it begins at the bottom line, and calls the lines indicated by the numbers as arguments.

```
>> Output 1

```

calls the function stored on line 1, then outputs the result. Line 1 is

```
> "cba"

```

, a nilad line which returns a single value and takes no arguments. Here, it returns the string `cba`, which is then outputted by the last line.

# Answer
> 0 votes
# PHP & HTML, 15 bytes

```
<?die(abc)?>cba

```

PHP exits with printing `abc`; `cba` is ignored.
HTML sees the PHP code as unrecognized tag (and ignores it), then prints `cba`.

# Answer
> 0 votes
# Bash / 05AB1E, 27 bytes

```
"printf" "abc\n" '#' r.ÁR¦¦

```

Try it online Bash

```
"printf" "abc\n" '#' r.ÁR¦¦
 │        │       └useless arguments
 │        └abc\n argument
 └printf command

```

Try it online! 05AB1E

```
"printf" "abc\n" '#' r.ÁR¦¦
 │        │       │ ││ │  └remove first two chars
 │        │       │ ││ └rotate stack 1 right
 │        │       │ │└reverse stack
 │        │       │ └push space character to stack
 │        │       └push # character to stack
 │        └push string "abc\n" to stack
 └push string "printf" to stack

```

---

# Bash / 05AB1E, 24 bytes (without new line)

```
"printf" "abc" '#' r.ÁR?

```

Try it online Bash

```
"printf" "abc" '#' r.ÁR?
 │        │     └useless arguments
 │        └abc argument
 └printf command

```

Try it online!

```
"printf" "abc" '#' r.ÁR?
 │        │     │ ││ │ └print stack without newline
 │        │     │ ││ └rotate stack 1 right
 │        │     │ │└reverse stack
 │        │     │ └push space character to stack
 │        │     └push # character to stack
 │        └push string "abc\n" to stack
 └push string "printf" to stack

```

# Answer
> 0 votes
# A0A0 and FiM++, 123 bytes

```
(
>P97
P98
P99

)
Dear Princess Celestia: A!
Today I learned B.
I said "cba"!
That's all about B!
Your faithful student, C.

```

The parentheses at the top open a block comment in FiM++, so the A0A0 code in it is ignored by FiM++. A0A0 starts at the second line because of the preceding `>` and then print "abc", halting on the empty line after it. FiM++ ignores the block comment and just executes a basic program that prints "cba". The first and last lines are for the class declaration, the second and fourth lines are for the main method, with the third line actually printing "cba".

---
Tags: code-golf, string, polyglot
---


title: KITT car ASCII art

text:
# Question
Title: KITT car ASCII art
The 80's TV series *Knight Rider* featured an intelligent, self-aware car called KITT. One distinctive aspect of the car was a front-mounted scanner bar that allowed KITT to "see" (and that looked suspiciously familiar to fans of another, earlier TV series).

The scanner had eight lights as seen in this picture:

The lights "moved" as shown in this animated image.

Your task, as you have guessed by now, it to recreate the scanner bar with the moving lights in ASCII art.

# The challenge

Given an integer `t`, output the state of the scanner bar at that instant, defined as follows:

* The scanner consists of eight lights.
* At any instant one of the lights is *active*, and is shown as `#`. The lights that were active at times `t-1` and `t-2` are now *dimmed*, and are shown as `+`; unless they coincide with the current active one. The rest of the lights are *off*, and are shown as `-`.
* The active light moves left to right, then right to left.

The exact output for each `t` is detailed below.

```
0  -->  #++-----   % The leftmost light is active, and it just came from the right.
                   % The two neighbouring lights are dimmed
1  -->  +#------   % The active light has bounced to the right, and it is covering
                   % one of the two lights that should be dimmed. So there is only
                   % one dimmed light
2  -->  ++#-----   % The active light has moved one more step to the right, and the
                   % two trailing dimmed lights are visible
3  -->  -++#----
7  -->  -----++#
8  -->  ------#+   % The active light has bounced to the left
9  -->  -----#++
10 -->  ----#++-
13 -->  -#++----
14 -->  #++-----   % Same as 0
15 -->  +#------   % Same as 1

```

For negative values of `t` the cycle is simply extended:

```
-1 -->  -#++----   % Same as 13
-2 -->  --#++---   % Same as 12

```

#Additional rules

You can write a program or function.

Output can contain trailing whitespace and a leading newline.

Shortest code in bytes wins.

# Answer
> 4 votes
# Jelly, ~~28~~ 22 bytes

-6 bytes thanks to the help of @Dennis! (upend first, then concatenate)

```
”-ẋ6;“#++”ṙ7Ḷ’¤Ḋ€U;$⁸ị

```

TryItOnline
Or perform four oscillations with a bonus **easter egg!!**

### How?

```
”-ẋ6;“#++”ṙ7Ḷ’¤Ḋ€U;$⁸ị - Main link: n
”-   “#++”             - strings "-" and "#++"
  ẋ6                   - repeat six times: "------"
    ;                  - concatenate: "------#++"
              ¤        - nilad followed by atoms as a nilad (ie make a constant)
           7Ḷ’         -     range(7) decremented: [-1,0,1,2,3,4,5]
          ṙ            - rotate left by (makes)-----------> ["+------#+",
               Ḋ€      - Dequeue each                        "------#++",
                   $   - last two atoms as a monad           "-----#++-",
                 U     -     reverse (vectorises)            "----#++--",
                  ;    -     concatenate                     "---#++---",
                    ⁸  - left argument (n)                   "--#++----",
                     ị - index into (1 based and modular)    "-#++-----"])

```

# Answer
> 6 votes
## JavaScript (ES6), ~~65~~ 67 bytes

**EDIT** \- Fixed for negative values. Now supporting `N >= -8,000,000,000`, which should provide a fairly good extended operating time in AUTO CRUISE mode. :-)

```
let f =

n=>[..."------#++-----".substr((n+=8e9)%7,8)].sort(_=>n/7&1).join``

// testing 28 frames
for(var i = -14; i < 14; i++) {
  console.log(f(i));
}
```

### Animated version

```
let f =

n=>[..."------#++-----".substr((n+=8e9)%7,8)].sort(_=>n/7&1).join``

let n = 0;

setInterval(function() { document.getElementById("o").innerHTML = f(n++) }, 90);
```

```
<pre id="o"></pre>
```

# Answer
> 4 votes
## JavaScript (ES6), ~~90~~ 87 bytes

```
n=>"01234567".replace(/./g,i=>"-+##"[g=n=>!((+i+n)%14&&(n-i)%14),g(n)*2|g(n-1)|g(n-2)])

```

"-+##" is indexed by a bitmask, where bit 1 signifies an active light and bit 0 signifies a dimmed light. Active/dimmedness is now calculated by adding and subtracting the current position from the desired position and seeing if either result is divisible by 14.

# Answer
> 4 votes
## Python, 53 bytes

```
lambda n:('-'*5+'++#'+'-'*6)[-n%7:][:8][::-n/7%2*2-1]

```

Creates the string `-----++#------`, takes a length-8 window depending on the input modulo 7, reverses for inputs modulo 14 that lie between 1 and 7 .

# Answer
> 3 votes
# MATL, ~~34~~ ~~30~~ 27 bytes

```
'++#-'I:7XyY+4LZ)t2&P&viY))

```

*7 bytes saved thanks to @Luis*

**Try it Online!**

Another example with the first 25 steps

**Explanation**

```
'++#-'      % Push the string literal to the stack
I:          % Create the array [1 2 3]
7Xy         % Create a 7 x 7 identity matrix
Y+          % Perform 2D convolution between the vector and this matrix
4LZ)        % Grab all but the first column. Yields the following matrix
            %
            %    2 3 0 0 0 0 0 0
            %    1 2 3 0 0 0 0 0
            %    0 1 2 3 0 0 0 0
            %    0 0 1 2 3 0 0 0
            %    0 0 0 1 2 3 0 0
            %    0 0 0 0 1 2 3 0
            %    0 0 0 0 0 1 2 3
            %
t2&P&v      % Copy this matrix, flip it horizontally and vertically concatenate
            % it with itself.
i           % Explicitly grab the input (n)
Y)          % Get the n-th row of the above matrix (and use modular indexing)
)           % Index into the initial string literal to replace 2 with #, 1 and 3 with +
            % and all 0's with -
            % Implicitly display the result

```

# Answer
> 3 votes
# \>\<\>, 51+3 = 54 bytes

```
<v{"------#++"%7&(7%*27:-1
}>:?!\1-$
{~&?r\~
l?!;o>

```

Input is expected on the stack at program start, so +3 bytes for the `-v` flag.

Try it online!

# Answer
> 2 votes
# Pyth, ~~33~~ 28 bytes

Saved 5 bytes by calculating all the lights the same way.

```
X:*8\-@LJ+U7_S7,-Q2tQ\+@JQ\#

```

Starts with the lights all off and turns them on one at a time.

Try it out online!

# Answer
> 2 votes
# JavaScript (ES6), 72

```
t=>`------${(t=(13+t%14)%14)>6?'#++':'++#'}------`.substr(t>6?t%7:7-t,8)

```

*Less golfed*

```
t=>(
  pad = '------',
  t = (13+(t%14))%14,
  u = t % 7,
  t > 6 ? (pad + '#++' + pad).substr(u, 8)
        : (pad + '++#' + pad).substr(7 - u, 8)
)

```

**Test**

```
f=
t=>`------${(t=(13+t%14)%14)>6?'#++':'++#'}------`.substr(t>6?t%7:7-t,8)

T=_=>(
  O.textContent=f(++N.textContent),
  setTimeout(T, 150)
)

T()
```

```
<input id=I type=number value=0 oninput='N.textContent=this.value'>
<pre id=N>-100</pre>
<pre id=O></pre>
```

# Answer
> 2 votes
## JavaScript, 204 bytes

```
function g(i){var a=(i%16+16)%16
if(!a)return g(2)
if(1==a%14)return(g(2)+'-').substr(1)
if((1<a)&&(a<8))return Array(a-1).join('-')+'++#'+Array(8-a).join('-')
return g(a-7).split("").reverse().join("")}

```

**Test**

```
function g(i){var a=(i%16+16)%16
if(!a)return g(2)
if(1==a%14)return(g(2)+'-').substr(1)
if((1<a)&&(a<8))return Array(a-1).join('-')+'++#'+Array(8-a).join('-')
return g(a-7).split("").reverse().join("")}

for (var i = 0; i < 16; ++i) {
    console.log(i + '-->' + g(i));
}
```

# Answer
> 2 votes
# Vim, 95 bytes

```
D7i-<esc>7a_<esc>@=(<C-r>"%14+13)%14+1
|r#8|i
<esc>:v/#/d
:s/.#/+#
f#i+<esc>:s/\v^(_*)(\+*)#(_*)$/\3#\2\1
:s/_/-/g

```

Try it online!

## Explanation

There might be a better way to do this...

```
D

```

Delete the input number into the `"` register.

```
7i-<esc>7a_<esc>

```

Insert the string `-------_______`.

```
@=...
|

```

Go to the character with the 1-based index given by this expression...

```
<C-r>"%14

```

The previously deleted number, mod 14. Unfortunately, Vim's mod operator gives negative results if the left-hand side was negative, so we have to correct for that...

```
(...+13)%14+1

```

... by adding 14 and taking the result mod 14. But at the same time, we can subtract 1, mod 14, and add 1 to give the 1-based mod (same as the regular mod, except it gives 14 instead of 0).

```
r#

```

Replace the character at that index (`-` or `_`) with `#`.

```
8|i
<esc>

```

Go to index 8 and insert a newline, putting the `-`s and the `_`s each on their own line.

```
:v/#/d

```

Whichever line doesn't contain the `#`, delete it.

```
:s/.#/+#

```

If there's a character before the `#`, replace it with `+`.

```
f#i+<esc>

```

Go to the `#` and insert another `+` before it.

```
:s/\v^(_*)(\+*)#(_*)$/\3#\2\1

```

If the line has `_` instead of `-`, reverse it.

```
:s/_/-/g

```

Replace `_` with `-`.

# Answer
> 1 votes
# Perl, ~~56~~ 55 bytes

Includes +3 for `-p`

Run with the number on STDIN:

```
for i in 0 `seq 14`; do kitt.pl <<< $i; echo; done

```

`kitt.pl`:

```
#!/usr/bin/perl -p
$_=eval'1x8
|1x(7-abs$_--%14-7).++$^F#'x3;y;1537;-+#

```

Put this in a file ***without*** the final newline (add a final `;` to the program if you don't want to bother with that). Unfortunately using a literal `^F` doesn't work

This program contains 2 comment characters (ignore the `#!` line). One of them really is a comment and actually ***gains*** a byte....

Implements the actual afterglow algorithm

# Answer
> 1 votes
# Perl, 65 bytes

Includes +1 for `-n`

Run with the number on STDIN:

```
for i in 0 `seq 14`; do perl -M5.010 kitt.pl <<< $i; done

```

`kitt.pl`:

```
#!/usr/bin/perl -n
$_="311e".--$_%14+4e16|0;s/.(.{8})/$&|reverse/e;y/013/-+#/;say//

```

Not very competitive but deserves a post for the strange method

# Answer
> 1 votes
# Canvas, 23 bytes

```
±７％╵-８×#++１╋８ｍ⁸╷³╵％７＜？↔

```

Try it here!

---
Tags: code-golf, string, ascii-art
---


title: Greatest Common Gaussian Divisor

text:
# Question
Title: Greatest Common Gaussian Divisor
Gaussian integers are complex numbers \\$x+yi\\$ such that \\$x\\$ and \\$y\\$ are both integers, and \\$i^2 = -1\\$. The norm of a Gaussian integer \\$N(x+yi)\\$ is defined as \\$x^2 + y^2 = |x+yi|^2\\$. It is possible to define a Euclidean division for Gaussian integers, which means that it is possible to define a Euclidean algorithm to calculate a greatest common divisor for any two Gaussian integers.

Unfortunately, a Euclidean algorithm requires a well-defined modulo operation on complex numbers, which most programming languages don't have (e.g. Python, Ruby), meaning that such an algorithm fails.

### Gaussian division

It is possible to define the division \\$\frac a b = x+yi\\$ (where \\$a\\$ and \\$b\\$ are both Gaussian integers) as finding a quotient \\$q\\$ and a remainder \\$r\\$ such that

$$a = bq + r, \text{ and } N(r) \le \frac {N(b)} 2$$

We can further limit this to \\$q = m + ni\\$, where \\$-\frac 1 2 \< x - m \le \frac 1 2\\$ and \\$-\frac 1 2 \< y - n \le \frac 1 2\\$, and \\$r = b(x - m + (y - n)i)\\$

From here, a Euclidean algorithm is possible: repeatedly replace \\$(a, b)\\$ by \\$(b, r)\\$ until it reaches \\$(d, 0)\\$. \\$d\\$ can then be called the greatest common divisor of \\$a\\$ and \\$b\\$

Complex GCDs are not unique; if \\$d = \gcd(a, b)\\$, then \\$d, -d, di, -di\\$ are all GCDs of \\$a\\$ and \\$b\\$

---

You are to take 2 Gaussian integers \\$a, b\\$ as input and output \\$\gcd(a, b)\\$. You may take input in any convenient method, and any reasonable format, including two complex numbers, two lists of pairs `[x, y], [w, z]` representing \\$\gcd(x+yi, w+zi)\\$ etc. Additionally, the output format is equally lax.

You may output **any** of the 4 possible values for the GCD, and you don't need to be consistent between inputs.

If your language's builtin \\$\gcd\\$ function already handles Gaussian integers, and so would trivially solve this challenge by itself, please add it to the Community Wiki of trivial answers below.

This is , so the shortest code in bytes wins.

## Test cases

```
5+3i, 2-8i    -> 1+i
5+3i, 2+8i    -> 5+3i
1-9i,  -1-7i  -> 1+i
-1+0i, 2-10i  -> 1+0i  (outputting 1 here is also fine)
4+3i,  6-9i   -> 1+0i  (outputting 1 here is also fine)
-3+2i, -3+2i  -> 2+3i
-6+6i, 3+5i   -> 1+i
4+7i, -3-4i   -> 2+i
-3+4i, -6-2i  -> 1+2i
7-7i, -21+21i -> 7+7i

```

# Answer
> 7 votes
# Python 3, 70 bytes

```
f=lambda a,b:b and f(b,a-b*((t:=a/b+.5+.5j).real//1+t.imag//1*1j))or a

```

# Answer
> 6 votes
# Community Wiki answer for trivial answers

Please add your language to this if the builtin GCD function correctly handles Gaussian integers.

## , 2 bytes

```
+.

```

Try it online!

## Wolfram Language (Mathematica), 3 bytes

```
GCD

```

Try it online!

## Pari/GP, 3 bytes

```
gcd

```

Try it online!

---
Tags: code-golf, math, complex-numbers
---


title: Smallest Diversifying Exponent

text:
# Question
Title: Smallest Diversifying Exponent
A *pandigital number* is an integer which contains every digit from 0 to 9 at least once. 1234567890, 1902837465000000, and 9023289761326634265 are all pandigital. For the purposes of this challenge, numbers such as 123456789 are not pandigital, since they do not contain a 0, even though 123456789 = 0123456789.

A *diverse* pair of integers is a pair of integers \\$(a, b)\\$ such that \\$a^b\\$ is pandigital. \\$b\\$ is called the *diversifying exponent*.

**Challenge:** Given an integer \\$a\\$, find the **smallest** corresponding diversifying exponent \\$b\\$. This is a , so the shortest program in bytes wins.

(You may assume that there exists such an exponent, that is, your program will not be given invalid input, such as a power of 10.)

Your solution must be able to handle at the minimum the given test cases, but it should theoretically handle all valid inputs.

This is A090493 on OEIS.

## Test cases

```
2 -> 68
3 -> 39
4 -> 34
5 -> 19
6 -> 20
7 -> 18
8 -> 28
9 -> 24
11 -> 23
12 -> 22
13 -> 22
14 -> 21
15 -> 12
16 -> 17
17 -> 14
18 -> 21
19 -> 17
20 -> 51
21 -> 17
22 -> 18
23 -> 14
24 -> 19
25 -> 11
26 -> 18
27 -> 13
28 -> 11
29 -> 12
30 -> 39
31 -> 11
32 -> 14
33 -> 16
34 -> 14
35 -> 19
36 -> 10
1234567890 -> 1

```

# Answer
> 10 votes
# Brachylog (v2), 9 bytes

```
;.≜^dl10∧

```

Try it online!

This is a function submission. The TIO link contains a wrapper that makes a function into a full program.

## Explanation

```
;.≜^dl10∧
 .≜        Brute-force all integers, outputting the closest to 0
;  ^         for which {the input} to the power of the number
    d        has a list of unique digits
     l10     of length 10
        ∧  (turn off an unwanted implicit constraint)

```

# Answer
> 6 votes
# Python 2, 44 bytes

```
f=lambda n,k=1:11>len(set(`k`))and-~f(n,n*k)

```

Input has to be a long, as ``k`` behaves differently for longs and ints.

Try it online!

# Answer
> 4 votes
# , 25 bytes

```
>:@]^:(10>#@~.@":@^)^:_&1

```

Try it online!

Single monadic verb. The input should be an extended-precision integer (e.g. `2x`).

### How it works

```
>:@]^:(10>#@~.@":@^)^:_&1    Monadic verb. Input: base a
    ^:              ^:_      Good old do-while loop.
                       &1    Given 1 as the starting point for b,
>:@]                         increment it each step
      (            )         and continue while the condition is true:
               ":@^          Digits of a^b
            ~.@              Unique digits
          #@                 Count of unique digits
       10>                   is less than 10

```

# Answer
> 4 votes
# Perl 6, 32 bytes

```
{first ($_** *).comb.Set>9,1..*}

```

Try it online!

Pretty self-explanatory.

### Explanation

```
{                              }  # Anonymous code block
first                     ,1..*   # First positive number that
      ($_** *)    # When the input is raised to that power
              .comb.Set    # The set of digits
                       >9  # Is longer than 9

```

# Answer
> 3 votes
# JavaScript (Node.js),  ~~51 46~~  43 bytes

Takes input as a BigInt literal. Returns **true** instead of **1**.

```
f=(n,k=n)=>new Set(n+'').size>9||1+f(n*k,k)

```

Try it online!

# Answer
> 3 votes
# 05AB1E (legacy), ~~10~~ 9 bytes

Saved 1 byte thanks to *Mr. Xcoder*

```
XµINmÙgTQ

```

Try it online!

**Explanation**

```
Xµ           # find the first positive integer N that
  INm        # when the input is raised to N
     Ù       # and duplicate digits are removed
      g      # has a length
       TQ    # equal to 10

```

# Answer
> 3 votes
# Ruby, 41 bytes

```
->n{i=0;i+=1until(n**i).digits.uniq[9];i}

```

Try it online!

# Answer
> 3 votes
## Haskell, 50 bytes

```
f a=until(\b->all(`elem`show(a^b))['0'..'9'])(+1)1

```

Try it online!

Same byte count:

```
f a=[b|b<-[1..],all(`elem`show(a^b))['0'..'9']]!!0

```

# Answer
> 2 votes
# Charcoal, 19 bytes

```
ＷΦχ¬№ＩＸＩθＬυＩκ⊞υωＩＬυ

```

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

```
ＷΦχ¬№ＩＸＩθＬυＩκ⊞υω

```

Repeatedly push the empty string to the empty list until there are no digits that the power of the input to the length of the list does not contain.

```
ＩＬυ

```

Print the length of the list.

# Answer
> 2 votes
# K (ngn/k), 76 bytes

```
{#{10>#?(+/|\0<|x)#x}{{+/2 99#,/|0 10\x,0}/+/99 99#,/a*\:x,0}\a::|(99#10)\x}

```

Try it online!

`{` `}` function with argument `x`

`|(99#10)\x` we represent numbers as reversed lists of 99 decimal digits - do that to the argument

`a::` assign to global variable `a` (k has no closures. we need `a` to be global so we can use it in subfunctions)

`{` `}{` `}\` while the first function returns falsey, keep applying the second function (aka while loop), preserving intermediate results

`a*\:x` each of `a`'s digits multiplied by each of `x`'s digits ("outer product")

`99 99#a*\:x,0` add an extra column of 0s and reshape again to 99x99, this shifts the i-th row by i items to the right, inserting 0s on the left (this works for the tests, for larger inputs 99x99 might lead to overflows)

`+/` sum

`{+/2 99#,/|0 10\x,0}/` propagate carry:

* `{` `}/` keep applying until convergence
* `0 10\x` divmod by 10 (a pair of lists)
* `|0 10\x` moddiv by 10
* `2 99#,/|0 10\x,0` moddiv by 10, with the "div" part shifted 1 digit to the right
* `+/` sum

`{10>#?(+/|\0<|x)#x}` \- check for (not) pandigital:

* `|x` reverse `x`
* `0<` which digits are non-zero
* `|\` partial maxima
* `+/` sum - this counts the number of leading 0s in `x`
* `10>` are they fewer than 10?

`#` length of the sequence of powers - this is the result

# Answer
> 2 votes
# Pyth, ~~10~~ 8 bytes

```
fq;l{`^Q

```

Try it online here.

```
fq;l{`^QT   Implicit: Q=eval(input())
            Trailing T inferred
f           Return (and print) the first positive integer where the following is true:
      ^QT     Raise input to the current number-th power
     `        Convert to string
    {         Deduplicate
   l          Take the length
 q            Is the above equal to...
  ;           10

```

*Saved 2 bytes thanks to FryAmTheEggman, previous code `fq;l{j^QT;`*

# Answer
> 2 votes
# Vyxal, 11 bytes

```
λ?neSUL₀=;ṅ

```

Try it Online!

```
λ               ;ṅ                # First truthy integer n where
  ?ne                              # When raised to input^n
        SUL₀=                   # Length of unique digits is 10

```

# Answer
> 1 votes
# Jelly, ~~12~~ 11 bytes

```
1*@ṾØDfƑʋ1#

```

Try it online!

### How it works

```
1*@ṾØDfƑʋ1#  Main link. Argument: n

1            Set the return value to 1.
         1#  Call the link to the left for k = 1, 2, ... and with right argument n,
             until it returns a truthy value.
        ʋ      Combine the four links to the left into a dyadic chain.
 *@              Compute n**k.
   Ṿ             Convert it to its string representation.
    ØD           Yield "0123456789".
      fƑ         Filter and return 1 is the result is equal to the left argument.

```

# Answer
> 1 votes
# Racket, 110 96 bytes

-14 bytes thanks to UltimateHawk!

```
(define(f n[b 1])(if(= 10(length(remove-duplicates(string->list(~v(expt n b))))))b(f n(+ b 1))))

```

Try it online!

# Answer
> 1 votes
# Tcl, 82 bytes

```
proc X d {while {[llength [lsort -u [split [expr $d**[incr i]] ""]]]-10} {}
set i}

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~52~~ 47 bytes

thanks to @BMO

```
f=lambda n,i=1:len({*str(n**i)})>9or 1+f(n,i+1)

```

Try it online!

# Answer
> 1 votes
# Java, 108 bytes

```
a->{int b=0;while(new java.math.BigDecimal(a).pow(++b).toString().chars().distinct().count()<10);return b;};

```

Try it online!

**Explanation**

Brute force, looping a^b until it finds a string with 10 (or more, but that's impossible as there will only be 0 through 9) unique characters.

`BigDecimal` is required both because `Math.pow` is not accurate enough (fails on case `11`), and also because converting a `Double` to a String by default shows scientific notation, which breaks this method of finding a pandigital number.

# Answer
> 1 votes
## `d`, ~~8~~ 5 bytes

This answer was made to fullfill lirtosiast's bounty.

```
Ö↕,╣⌡

```

Uncompressed:

```
xUT=iX

```

## Explanation

```
    iX % For every item in the range from 1 to infinity:
x      % Exponentiate b with a
 U     % Uniquify the value (Numbers are cast to a string)
  T=   % Is the length equal to 10?
       % (Due to the unique mechanism in W, this finds the length
       % of the string before the operation is done.)
       % If that's true, output the number and halt.

```

# Answer
> 0 votes
# PowerShell, 107 bytes

```
param([bigint]$a)for([bigint]$b=1;-join("$([bigint]::pow($a,$b))"|% t*y|sort -u)-ne-join(0..9);$b=$b+1){}$b

```

Try it online!

Pretty straightforward, just a shame we need to use `[bigint]` everywhere. We take input `$a`, then setup a `for` loop with initializer `$b=1`.

Each iteration we increment `$b` after checking whether `$a ^ $b` (via `pow`) sent `t`oCharArra`y`, `sort`ed with the `-u`nique flag, then `-join`ed together into a string is `-n`ot`e`qual to the range `0..9` also `-join`ed into a string.

That's a mouthful. For example, this would compare `7 ^ 5 = 16807 --> "01678"` against `"0123456789"`, determine they're not equal, and continue the loop.

Once we're out of the loop, we've determined which `$b` suits our input, and so leave that on the pipeline. Output is implicit.

# Answer
> 0 votes
# Clean, ~~107~~ 101 bytes

```
import StdEnv,Data.Integer
$a=hd[b\\b<-[1..]|length(removeDup[c\\c<-:toString(prod(repeatn b a))])>9]

```

Try it online!

Takes input as `Integer`, returns `Int`

# Answer
> 0 votes
# Wolfram Language (Mathematica), 48 bytes

```
(For[n=1,!AllTrue[DigitCount[#^n],#>0&],n++];n)&

```

Try it online!

# Answer
> 0 votes
# Attache, 27 bytes

```
${Generate{#Unique[x^_]>9}}

```

Try it online!

## Explanation

```
${Generate{#Unique[x^_]>9}}
${                        }    lambda, input: x
  Generate{              }     first natural number _ satisfying...
                   x^_             the input to that number
            Unique[   ]          unique digits of ^
           #                   length of ^
                       >9      is greater than 9
                               i.e.: has 10 distinct digits

```

## Alternatives

**28 bytes:** `${Generate{Unique@S[x^_]@9}}`

**29 bytes:** `${Generate{Unique[S[x^_]]@9}}`

**30 bytes:** `${Generate{#Unique[S[x^_]]>9}}`

**31 bytes:** `Generate@${{#Unique[S[x^_]]>9}}`

**32 bytes:** `${Generate[{#Unique[S[x^_]]>9}]}`

**33 bytes:** `${If[#Unique[x^y]>9,y,x&$!-~y]}&0`

**34 bytes:** `${If[#Unique[x^y]>9,y,$[x,y+1]]}&0`

# Answer
> 0 votes
# GolfScript, 20 bytes

```
:i;0{).i\?`.|,10<}do

```

My first stab at it, pretty happy with my solution.

TLDR; Takes i as the base, and makes a 0. Open block. Incrememnt that 0 by 1, then put it as an exponent of i. Turn it into a string, then check how many characters there are. If 10, stop. If not, repeat block.

Successful exponent printed on program termination.

Try it online!

# Answer
> 0 votes
# Perl 5 `-Mbigint -n`, ~~61~~ 43 bytes

```
$t=$_**($p+=1)while grep$t!~/$_/,0..9;say$p

```

Try it online!

# Answer
> 0 votes
# Burlesque, 18 bytes

```
rir0?^{NBL[10==}fi

```

Try it online!

```
ri      # Read input as int
r0      # Range [0,inf]
?^      # Raise to power
{
 NB     # Unique digits
 L[10== # Length == 10
}fi     # Find index of first which

```

---
Tags: code-golf, math
---


title: Approximate My Squares

text:
# Question
Title: Approximate My Squares
*Inspired by this video by tecmath*.

An approximation of the square root of any number `x` can be found by taking the integer square root `s` (i.e. the largest integer such that `s * s ≤ x`) and then calculating `s + (x - s^2) / (2 * s)`. Let us call this approximation `S(x)`. (Note: this is equivalent to applying one step of the Newton-Raphson method).

Though this does have quirk, where S(n^2 - 1) will always be √(n^2), but generally it will be very accurate. In some larger cases, this can have a \>99.99% accuracy.

## Input and Output

You will take one number in any convienent format.

## Examples

Format: Input -\> Output

```
2 -> 1.50
5 -> 2.25
15 -> 4.00
19 -> 4.37               // actually 4.37       + 1/200
27 -> 5.20
39 -> 6.25
47 -> 6.91               // actually 6.91       + 1/300
57 -> 7.57               // actually 7.57       + 1/700
2612 -> 51.10            // actually 51.10      + 2/255
643545345 -> 25368.19    // actually 25,368.19  + 250,000,000/45,113,102,859
35235234236 -> 187710.50 // actually 187,710.50 + 500,000,000/77,374,278,481

```

## Specifications

* Your output must be rounded to at least the nearest hundredth (ie. if the answer is 47.2851, you may output 47.29)
* Your output does not have to have following zeros and a decimal point if the answer is a whole number (ie. 125.00 can be outputted as 125 and 125.0, too)
* You do not have to support any numbers below 1.
* You do not have to support non-integer inputs. (ie. 1.52 etc...)

## Rules

Standard Loopholes are forbidden.

This is a , so shortest answer in bytes wins.

# Answer
> 2 votes
# Jelly,  ~~8~~  7 bytes

-1 byte thanks to Olivier Grégoire's simplified mathematical formula - see their Java answer.

```
÷Æ½+Æ½H

```

**Try it online!**

### How?

```
÷Æ½+Æ½H - Link: number, n
 Æ½     - integer square root of n  -> s
÷       - divide                    -> n / s
    Æ½  - integer square root of n  -> s
   +    - add                       -> n / s + s
      H - halve                     -> (n / s + s) / 2

```

# Answer
> 4 votes
# Python 2, ~~47~~ ... 36 bytes

*-3 bytes thanks to @JungHwanMin*
*-1 byte thanks to @HyperNeutrino*
*-2 bytes thanks to @JonathanFrech*
*-3 bytes thanks to @OlivierGrégoire*

```
def f(x):s=int(x**.5);print(x/s+s)/2

```

Try it online!

# Answer
> 4 votes
# R, ~~43 bytes~~ 29 bytes

```
x=scan()
(x/(s=x^.5%/%1)+s)/2

```

Thanks to @Giuseppe for the new equation and help in golfing of 12 bytes with the integer division solution. By swapping out the function call for scan, I golfed another couple bytes.

Try it online!

# Answer
> 4 votes
# Java (OpenJDK 8), 32 bytes

```
n->(n/(n=(int)Math.sqrt(n))+n)/2

```

Try it online!

## Explanations

The code is equivalent to this:

```
double approx_sqrt(double x) {
  double s = (int)Math.sqrt(x);  // assign the root integer to s
  return (x / s + s) / 2
}

```

The maths behind:

```
s + (x - s²) / (2 * s)  =  (2 * s² + x - s²) / (2 * s)
                        =  (x + s²) / (2 * s)
                        =  (x + s²) / s / 2
                        =  ((x + s²) / s) / 2
                        =  (x / s + s² / s) / 2
                        =  (x / s + s) / 2

```

# Answer
> 4 votes
# Haskell, 34 bytes

```
f x=last[s+x/s|s<-[1..x],s*s<=x]/2

```

Try it online!

Explanation in imperative pseudocode:

```
results=[]
foreach s in [1..x]:
 if s*s<=x:
  results.append(s+x/s)
return results[end]/2

```

# Answer
> 3 votes
# APL (Dyalog), ~~20~~ 16 bytes

```
{.5×s+⍵÷s←⌊⍵*.5}

```

Try it online!

# Answer
> 3 votes
# MATL, ~~12~~ 9 bytes

```
X^kGy/+2/

```

Try it online!

# Answer
> 2 votes
# C, 34 bytes

*Thanks to @Olivier Grégoire!*

```
s;
#define f(x)(x/(s=sqrt(x))+s)/2

```

Works only with `float` inputs.

Try it online!

# C,  ~~41~~   ~~39~~  37 bytes

```
s;
#define f(x).5/(s=sqrt(x))*(x+s*s)

```

Try it online!

# C,  ~~49~~   ~~47~~   ~~45~~  43 bytes

```
s;float f(x){return.5/(s=sqrt(x))*(x+s*s);}

```

Try it online!

---

*Thanks to @JungHwan Min for saving two bytes!*

# Answer
> 2 votes
# JavaScript (ES7), 22 bytes

```
x=>(s=x**.5|0)/2+x/s/2

```

We don't really need an intermediate variable, so this can actually be rewritten as:

```
x=>x/(x=x**.5|0)/2+x/2

```

### Test cases

```
let f =

x=>x/(x=x**.5|0)/2+x/2

console.log(f(2))           // 1.50
console.log(f(5))           // 2.25
console.log(f(15))          // 4.00
console.log(f(19))          // 4.37
console.log(f(27))          // 5.20
console.log(f(39))          // 6.25
console.log(f(47))          // 6.91
console.log(f(57))          // 7.57
console.log(f(2612))        // 51.10
console.log(f(643545345))   // 25368.19
console.log(f(35235234236)) // 187710.50
```

# Answer
> 2 votes
# Haskell, 40 bytes

*Another one bytes the dust thanks to H.PWiz.*

```
f n|s<-realToFrac$floor$sqrt n=s/2+n/s/2

```

Try it online!

# Answer
> 2 votes
# AWK, ~~47 44~~ 38 bytes

```
{s=int($1^.5);printf"%.2f",$1/2/s+s/2}

```

Try it online!

NOTE: The TIO like has 2 extra bytes for `\n` to make the output prettier. :)

It feels like cheating a bit to use sqrt to find the square root, so here is a version with a few more bytes that doesn't.

```
{for(;++s*s<=$1;);s--;printf("%.3f\n",s+($1-s*s)/(2*s))}

```

Try it online!

# Answer
> 2 votes
# Vyxal, 8 bytes

```
:√I:‟/+½

```

Try it Online!

For `n=2`

```
:        # Dup -> [2,2]
√        # Square root -> [2,√2]
I        # Round -> [2,1]
:        # Dup -> [2,1,1]
‟        # Rotate stack right -> [1,2,1]
/        # Divide -> [1,2]
+        # Add -> 3
½        # Halve -> 1.5

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
DtïD.Á/+;

```

Try it online!

Port of my Vyxal answer

# Answer
> 1 votes
# Racket, 92 bytes

Thanks to @JungHwan Min for the tip in the comment section

```
(λ(x)(let([s(integer-sqrt x)])(~r(exact->inexact(/(+ x(* s s))(* 2 s)))#:precision'(= 2))))

```

Try it online!

Ungolfed

```
(define(fun x)
  (let ([square (integer-sqrt x)])
    (~r (exact->inexact (/ (+ x (* square square)) (* 2 square)))
        #:precision'(= 2))))

```

# Answer
> 1 votes
# PowerShell, 54 bytes

```
param($x)($x+($s=(1..$x|?{$_*$_-le$x})[-1])*$s)/(2*$s)

```

Try it online! or Verify some test cases

Takes input `$x` and then does exactly what is requested. The `|?` part finds the maximal integer that, when squared, is `-l`ess-than-or-`e`qual to the input `$x`, then we perform the required calculations. Output is implicit.

# Answer
> 1 votes
# Milky Way, ~~17~~ 14 bytes

*-3 bytes by using Olivier Grégoire's formula*

```
^^':2;g:>/+2/!

```

Try it online!

## Explanation

```
code              explanation                   stack layout

^^                clear preinitialized stack    []
  ':              push input and duplicate it   [input, input]
    2;            push 2 and swap ToS and SoS   [input, 2, input]
      g           nth root                      [input, s=floor(sqrt(input))]
       :          duplicate ToS                 [input, s, s]
        >         rotate stack right            [s, input, s]
         /        divide                        [s, input/s]
          +       add                           [s+input/s]
           2/     divide by 2                   [(s+input/s)/2]
             !    output                        => (s+input/s)/2

```

# Answer
> 1 votes
# Husk, 9 bytes

```
½Ṡ§+K/(⌊√

```

Try it online!

There is still something ugly in this answer, but I can't seem to find a shorter solution.

### Explanation

I'm implementing one step of Newton's algorithm (which is indeed equivalent to the one proposed in this question)

```
½Ṡ§+K/(⌊√
  §+K/       A function which takes two numbers s and x, and returns s+x/s
 Ṡ           Call this function with the input as second argument and
      (⌊√    the floor of the square-root of the input as first argument
½            Halve the final result

```

# Answer
> 1 votes
# Pyt, ~~11~~ 10 bytes

```
←Đ√⌊Đ↔⇹/+₂

```

# Explanation

```
code                explanation                        stack
←                   get input                          [input]
 Đ                  duplicate ToS                      [input,input]
  √⌊                calculate s                        [input,s]
    Đ               duplicate ToS                      [input,s,s]
     ↔              reverse stack                      [s,s,input]
      ⇹             swap ToS and SoS                   [s,input,s]
       /            divide                             [s,input/s]
        +           add                                [s+input/s]
         ₂          halve                              [(s+input/s)/2]
                    implicit print

```

# Answer
> 0 votes
# C# (.NET Core), 39 bytes

```
v=>(v/(v=(int)System.Math.Sqrt(v))+v)/2

```

Try it online!

A C# version of Olivier Grégoire's Java answer.

---
Tags: code-golf, math, approximation
---


# Question
Title: What is the missing number (divisibility by 9)
## Challenge

Given a whole number divisible by 9 and one missing digit, find the missing digit.

The missing digit may be represented by any character other than the digits 0-9 as long as it is consistent.

If the missing digit could be 0 or 9, output something to signify so.

Assume the user is intelligent enough to put only one missing digit and one number etc.

## Test Cases

In the test cases the missing digit is represented by a question mark

```
123? -> 3
?999 -> 0 or 9
?0023 -> 4
000?1 -> 8

```

# Answer
> 17 votes
# Python, 21 bytes

```
lambda s:-int(s,19)%9

```

Try it online!

I used `I` to represent a missing digit.

# Answer
> 9 votes
## Alice, 12 bytes

```
/o&
\i@/+R9%

```

Try it online!

Outputs `0` if the result can be either 0 or 9.

### Explanation

```
/   Switch to Ordinal mode.
i   Read all input as a string.
&   Fold the next operation over the characters of this strings.
/   Switch to Cardinal mode (not an operation).
+   Add. Implicitly converts each character to the integer value it represents
    and adds it to the top of the stack. The top of the stack is initially, implicitly
    zero. When the character is "?", it is simply discarded, which adds the top of
    the stack to another implicit zero beneath, so the "?" is effectively skipped.
R   Negate. Multiplies the sum by -1.
9%  Modulo 9. This gives the result.
\   Switch to Ordinal mode.
o   Implicitly convert the result to a string and print it.
@   Terminate the program.

```

# Answer
> 6 votes
# JavaScript (ES6), 40 bytes

Outputs 9 if could be 0 or 9.

```
f=_=>9-([..._].reduce((a,b)=>a+~~b,0)%9)

```

# Answer
> 5 votes
# Japt, 7 bytes

Tried a few solutions but the shortest was similar to most others except we don't need to replace the `?` at the start.

Can take any non-numeric character as the missing digit. Outputs `0` when the solution can be that or `9`.

```
¬x*J u9

```

Try it

---

## Explanation

Implicit input of string `U`. `¬` splits to an array of individual characters, `x` reduces the array by addition ignoring any non-numeric elements, `*J` multiplies each element by -1 and `u9` gets the positive modulus of the result.

# Answer
> 5 votes
# JavaScript (ES6), 18 bytes

Expects a `+` as the missing digit. Returns `9` for *0 or 9*.

```
s=>9-eval(9+s+9)%9

```

### Test cases

```
let f =

s=>9-eval(9+s+9)%9

console.log(f('123+'))  // -> 3
console.log(f('+999'))  // -> 0 or 9
console.log(f('+0023')) // -> 4
console.log(f('000+1')) // -> 8
```

# Answer
> 4 votes
# Python 2, ~~44~~ ~~41~~ 35 bytes

-6 bytes thanks to RiaD

```
lambda n:-sum(ord(c)-3for c in n)%9

```

Try it online!

Users `]` for missing digit.
Outputs `0` if the missing digit could be 0 or 9.

# Answer
> 4 votes
# 05AB1E, ~~7~~ 6 bytes

An output of `0` means the result could be either **0** or **9**.

```
þSO(9%

```

Try it online! or as a Test suite

**Explanation**

```
þ        # remove non-digits from input
 S       # split to list of digits
  O      # sum list
   (     # negate
    9%   # mod by 9

```

# Answer
> 3 votes
# Jelly, ~~11~~ ~~9~~ 6 bytes

```
|0SN%9

```

### Explanation

```
|0     # Read input while removing non-digits (question marks) and removing leading zeros
  S    # Sum the digits
   N   # Negate
    %9 # Mod by 9

```

An output of 0 means the result could be either 0 or 9.

Try it online!

Saved 2 bytes thanks to Mr. Xcoder. When using the Each quick () during evaluation, splitting the number into digits was redundant.

Saved 3 bytes thanks to Dennis. Can bitwise OR the input with 0 instead of manually parsing the input as a number while removing leading zeros and non-digits.

# Answer
> 3 votes
# Pyth, ~~9~~ 7 bytes

```
%_s-Qd9

```

Uses space as the delimiter and returns 0 if the result could be 0 or 9.

Try it online

### Explanation

```
%_s-Qd9
   -Qd   Remove the space from the input.
  s      Convert it to an integer.
%_    9  Negate mod 9.

```

# Answer
> 3 votes
# Prolog (SWI), 59 bytes

```
0*[].
X*[H|T]:-between(0,9,H),U is mod(X+H,9),U*T.
+X:-0*X.

```

Try it online!

Yay for Logical programming!

## Explanation

First we make a predicate `*`, which holds when applied to zero and the empty list. Our predicate also holds when the front of the list is between 0 and 9 and when we add the leading digit mod 9 the predicate holds.

We then define `+` to just be this predicate with `0` as the first argument. That is we want the digital sum to be a multiple of 9.

Prolog does all the grunt work of actually finding solutions for us.

# Answer
> 3 votes
# Befunge-93, 16 bytes

```
1+!_#@3#.--9%~:#

```

Try it online!

A one line version of James Holderness’ Befunge answer that manages to shave off two bytes. This essentially compresses the code down to one line, reverses the direction and takes advantage of the fact that Befunge doesn’t skip at the end of the line. He suggested I post a separate answer with an explanation. The code takes an * as representing the missing digit and outputs a 9 for either 0 or 9.

### How It Works

```
1+!_  3  --9% Initialises the pointer going right and initialises the digitsum with 3

1+!_         ~: Gets input and checks whether it is end of input (-1)

      3  - Subtract three from the input.
           This turns the ASCII values of digits into their mod 9 equivalent ("0"(48)=>45(mod 9)=>0)

          -9% Subtract the value from the digitsum and mod it with 9
              This keeps the digitsum as a negative digit greater than -9
              Repeat this until the input ends

Now this is where it gets tricky.
At the end of input, the stack looks like this:
  -(Digitsum%9), Copy of EOF input (-1)
The pointer is moving left from the _
 +!_ Invert the -1 to get 0 and add it to the digitsum (does nothing but get rid of the -1)
1           %~ Adds 1 mod -1 (no input) = 0 to the stack
         --9 Subtracts 9 from 0, yielding -9 and subtracts that from the digitsum.
             This makes the digitsum positive and equal to 9-(digitsum%9), our desired value
     @  . Finally, print and exit

```

`*` (ASCII value 42) was chosen as the missing character because it counteracts the initial value of the digitsum, 3.

# Answer
> 2 votes
# , ~~14~~ 12 bytes

-2 bytes thanks to @BolceBussiere

```
9|9-[:+/"."0

```

I honestly don't know why `"."0` interprets `?` as 0 but it does so on my interpreter and on TIO so I'm not going to question it. (Update: see comments for an explanation why).

This approach very simply takes the sum of the digits, negates it by subtracting from 9, and takes it modulo 9.

Try it online!

# Answer
> 2 votes
## LaTeX, many bytes (~~1000~~ ~~628~~ 614)

```
\RequirePackage{expl3}
\ExplSyntaxOn
\tl_new:N \l_divnine_input_tl
\int_new:N \l_divnine_sum_int
\def \getnum {
  \typein [ \l_divnine_input_tl ] { Input\space a\space number }
  \tl_map_function:NN \l_divnine_input_tl \divnine_sum:n
  \int_set:Nn \l_tmpa_int { 9 - \int_mod:nn { \l_divnine_sum_int } { 9 } }
  \typeout
    { The\space missing\space digit\space is:\space
      \int_use:N \l_tmpa_int
      \int_compare:nNnT { \l_tmpa_int } = { 0 } { \space or\space 9 }
    }
}
\cs_new:Nn \divnine_sum:n {
  \regex_match:nnT { \d } { #1 } { \int_add:Nn \l_divnine_sum_int { #1 } }
}
\ExplSyntaxOff
\getnum
\stop

```

## LaTeX, illegible (~~348~~ 334 bytes)

```
\RequirePackage{expl3}\ExplSyntaxOn\int_new:N\1\tl_new:N\2\def\3{\typein[\2]{Input\space a\space number}\tl_map_function:NN\2\4\int_set:Nn\1{9-\int_mod:nn{\1}{9}}\typeout{The\space missing\space digit\space is:\space\int_use:N\1\int_compare:nNnT{\1}={0}{\space or\space9}}}\def\4#1{\regex_match:nnT{\d}{#1}{\int_add:Nn\1{#1}}}\3\stop

```

## LaTeX, 132 bytes

```
\RequirePackage{expl3}\typein[\1].\newcount\2{\ExplSyntaxOn\int_gset:Nn\2{9-\int_mod:nn\19}}\typeout{\the\2 \ifnum\2=9or 0\fi}\stop

```

Only space is allowed as unknown digit in this code.

# Answer
> 1 votes
# Befunge-93, ~~28~~ ~~27~~ ~~19~~ 18 bytes

Credit must go to Mistah Figgins, whose PyFunge answer showed me that you didn't need a special check for the missing digit character, if you just made sure the ASCII value was a multiple of nine.

Additional thanks to Jo King who showed that you didn't need to fully convert the characters to their numeric equivalent, and could simply subtract 3 to get a value that is relative to base 9 (ASCII `0` minus 3 is 45, a multiple of 9).

```
3_v#`0:~--
%9_@.+9

```

Try it online!

For this to work, you should use the character `*` for the missing digit (there are others that could also work, but that's the nicest).

Outputs `9` if the missing digit could be 0 or 9.

**Explanation**

```
3             Push 3 onto the stack.
 _            Since this is non-zero, drop the 3 and branch left.
3             Now executing right to left, push 3 again.
        --    Negate twice, leaving the value unchanged as our starting sum.

       ~      Now we start the main loop, reading a character from stdin.
    `0:       Duplicate and check if it's > 0, i.e. not end-of-stream.
 _ #          If so, continue to the left.
3        -    Subtract 3 to make the number relative to base 9.
        -     Then subtract it from the total, and repeat the loop.

  v           Once we reach the end of the input, we go down.
  _           Drop the EOF character from the stack and go left.
%9   +9       Mod the total with 9, and add 9.
   @.         Output the result and exit.

```

Essentially we are calculating the sum of all digits, plus 45 per digit (which will ultimately be cancelled out when we mod with 9). This sum is subtracted from 3 (our starting total), and an additional 39 is subtracted by the missing digit (ASCII `*` minus three). Again that 3 minus 39 is a multiple of 9, so it's cancelled out when we mod with 9.

So in the end we're calculating the negative sum of all the digits, mod 9, plus 9, i.e.

```
9 - (digitsum % 9)

```

And that's gives us the missing digit.

# Answer
> 1 votes
# Swift, 51 bytes

```
{9-Int("0"+$0.filter{"?" != $0})!%9}as(String)->Int

```

Try it online!

# Answer
> 1 votes
# Befunge-98 (PyFunge), ~~15~~ 13 bytes

I realized that I don't need to use `?` to represent the absent digit, so I used one that is a multiple of 9 after subtracting 48: `x`
This let me golf off the `3+`.

```
#v~'0-+
q>-9%

```

Try it online!

Uses an `x` as the missing digit, because it's ASCII value is divisible by 9 after subtracting 48 (and it's nice because its commonly used as a variable in math).

Outputs via exit code (because `q` is one byte shorter than `.@`)
Outputs `0` if the missing digit could be 0 or 9.

This only works in the PyFunge interpreter for reasons explained below.

### Explanation

In the first line of the program, we sum the digits, including the `x`, which is treated like a 72 because of it's ASCII value. However, the sum will be the same once we've modded by 9, so this is irrelevant.

```
#v~'0-+    THE FIRST LINE
#v~        Pushes the next character from input, and goes to the second line on EOF
   '0-     Subtracts 48 to account for taking in ASCII values
      +    Adds this adjusted value to the sum

```

If we just modded by 9, we would be left with the wrong digit, because we want `9 - (sum % 9)`. However, we can do better than `9\-`, which would subtract the remainder from 9: if we make the sum negative before modding by 9, we will get a positive result, equivalent to `9 - (sum % 9)` *in some interpreters*. This is what requires us to use the PyFunge interpreters for both Befunge 93 and 98, as it is the only one on TIO that does this. The others give us a value between -8 and 8 instead of 0 and 8.

```
q>-9%    THE SECOND LINE
 >       Redirects the IP onto this line
  -      Subtracts the sum from an implicit 0, making it negative
   9%    Mods the sum by 9
q        Outputs via exit code, ending the program

```

# Answer
> 1 votes
# Befunge-93 (PyFunge), ~~22~~ 21 bytes

I realized that I don't need to use `?` to represent the absent digit, so I used one that is a multiple of 9 after subtracting 48: `x`
This let me golf off the `3+`, but it only saved me 1 byte because of the length of the first line before the conditional :(

---

A port of my Befunge-98 answer:
5 more bytes in order to check if we've reached EOF,
1 more byte to push 48 (`"0"` vs `'0`),
1 more byte to print the answer with `.@`,
and 1 more byte, because the second line has a space
for a total of 8 more bytes.

```
~:0`!#|_"0"-+
 @.%9-<

```

Try it online!

Outputs `0` if the missing digit could be 0 or 9.

This only works in the PyFunge interpreter for reasons explained below.

### Explanation

Much of this explanation is copy-pasted from my Befunge-98 explanation, as that program is very similar to this one. shameless plug

In the first line of the program, we sum the digits, including the x, which is treated like a 72 because of it's ASCII value. However, the sum will be the same once we've modded by 9, so this is irrelevant.

```
~:0`!#|_"0"-+    THE FIRST LINE
~                Gets a character from input - If it is negative, we've reached EOF
 :0`!            Pushes 0 if the character is positive, 0 otherwise
     #|_         Goes to the next line if the value if 0
                     This also gets the negative value off the stack by using a |
        "0"-     Subtracts 48 to account for taking in ASCII values
            +    Adds this adjusted value to the sum

```

If we just modded by 9, we would be left with the wrong digit, because we want `9 - (sum % 9)`. However, we can do better than `9\-`, which would subtract the remainder from 9: if we make the sum negative before modding by 9, we will get a positive result, equivalent to `9 - (sum % 9)` in some interpreters. This is what requires us to use the PyFunge interpreters for both Befunge 93 and 98, as it is the only one on TIO that does this. The others give us a value between -8 and 8 instead of 0 and 8

```
 @.%9-<    THE SECOND LINE
      <    Redirects the IP onto this line
     -     Subtracts the sum from an implicit 0, making it negative
   %9      Mods the sum by 9
 @.        Prints the digit and exits

```

# Answer
> 1 votes
# Ruby, 46, 41 bytes

*-5 thanks to @Unihedron*

```
->s{-s.chars.sum{|i|?<>i ? i.to_i : 0}%9}

```

Try it online!

# Answer
> 1 votes
# Ruby, 22 bytes

Uses `'` (any char that has a distance to `0` that is divisible by "0" will do, including `0` itself).

An output of `0` signifies either `0` or `9`.

```
p -(gets.sum+6*~/$/)%9

```

Try it online!

## Explanation

```
p     # print after inspecting
  -(  # unary negative, for reversing result of modulus (a-b%a)
    gets.sum # ascii value of string
    + 6*~/$/ # add six for each size (in chars) of input, so "0" translates to 0
  )%9 # mod 9
      # find remainder after dividing 9
      # except it's inverted so it's remainder to add to divide 9

```

# Answer
> 1 votes
# APL (Dyalog), 13 bytes

```
{9-9|+/,↑⍎¨⍵}

```

Try it online!

The missing digit is .

# Answer
> 1 votes
# brainfuck, 50 bytes

```
+>,[---[<-[<<]>[<+++++++++<]>>-],]-[<+>-----]<---.

```

Try it online!

Prints a 9 for either 0 or 9. Missing character is represented by :

### How It Works

```
Tape Format:
    0 Total Input 0

The total is represented as 9-digitSum%9

+>,[ Start loop with 1 as the total
    --- Subtract 3 from the inputted byte to make the value%9 equal to the digit
    [   While the input byte exists
      <-                 Decrement the total
      [<<]>[<+++++++++<] If the total is 0, reset it to 9
      >>-                Decrement the input byte
    ]
,] Continue loop until there is no input
-[<+>-----]<---. Add 48 to the total to convert the digit to the ascii value and output it

```

The missing character needs to be a character that has a mod 9 of 4, +3 because we subtract 3 from the normal digits and +1 for the initialisation of the total as 1.

As a side note, there is a *lot* of inefficiency in the code for the sake of golfing, as each digit will reset the total 5 times each, rather than just once sometimes if I subtracted 48 instead of 3.

# Answer
> 1 votes
# Befunge-98 (PyFunge), 8 bytes

```
#q~3--9%

```

Try it online!

Outputs via exit code. As with Mistah Figgin's answer, it only works with Pyfunge, where a negative number mod 9 becomes positive. Uses an x as the missing digit.

# Answer
> 1 votes
# Java 8, ~~36~~ 34 bytes

```
s->9-s.map(c->c>57?0:c-48).sum()%9

```

Returns `9` when both `0` and `9` are valid.

**Explanation:**

Try it online.

```
s->                               // Method with IntStream parameter and int return-type
   9-                             //  Return 9, minus:
     s.map(c->c>57?0:c-48).sum()  //   The sum of the digits (ignoring the question mark)
     %9                           //   modulo-9

```

# Answer
> 1 votes
# Vyxal, 7 bytes

```
19βN9%‹

```

Try it Online!

# Answer
> 0 votes
# PowerShell, 40 bytes

```
param($a)0..9|?{!(($a-replace'x',$_)%9)}

```

Try it online! or Verify all test cases

Takes input like `'123x'` into `$a`. Constructs a range `0` to `9` and uses `Where-Object` (here abbreviated as `|?`) to pull out those integers that match the clause. The clause takes `$a`, performs a regex `-replace` to replace the `x` with the current digit `$_` and gets the mod 9 with `%9`. Thus if 9 evenly divides, this will be zero. We take the Boolean-not thereof, which turns the zeros truthy and everything else falsey, so that satisfies the Where-Object clause. Those result(s) are left on the pipeline and output is implicit.

# Answer
> 0 votes
# Retina, ~~35~~ ~~34~~ 25 bytes

If the `?` can be `0 or 9`, the result is shown as `9`.

```
.
$*
1{9}

^
9$*;
+`;1

.

```

**Try it online**

### Explanation

```
.       Sum of the digits in unary + 1
$*
1{9}    Modulo 9

^       Prepend 9 semicolons, for subtracting
9$*;
+`;1    Subtract from 9

.       Back to decimal

```

# Answer
> 0 votes
# \>\<\>, ~~35~~ ~~33~~ ~~25~~ ~~21~~ 15 bytes

An output of `0` means the result could be either **0** or **9**.

```
0i:&0(?n&3--9%!

```

Try it online!

Saved 6 bytes thanks to *Jo King* by using `'` to represent missing digits.

# Answer
> 0 votes
# Pyth, 8 bytes

```
%_iz19 9

```

Try it online!

Uses `I` instead of `?`.

* Convert to base 19.
* Negate.
* Modulo 9.

# Answer
> 0 votes
# Haskell, 35 bytes

```
f s=9-sum[read[i]|i<-s,i<':']`mod`9

```

Try it online!

# Answer
> 0 votes
# Perl 5, 23 bytes

```
$_=- s/\D//r%9;s/0/0|9/

```

Try it online!

Doesn't care what character signifies the missing digit as long as it isn't a digit.

# Answer
> 0 votes
# Tcl, 53 bytes

```
puts [expr 9-([regsub -all (\\d)\\D? 0$argv +\\1])%9]

```

As with other answers, this is made shorter by not explicitly saying “0 or 9”.
Instead, a result of “9” means either 0 or 9.

Try it online!

**Explanation**

It works pretty simply. It employs a regular expression to:

* split the argument into individual digits
* eliminate any ~~question mark(s)~~ non-digit(s)
* interleave the digits with plus signs

It then evaluates 9 - (sum\_of\_digits mod 9) to arrive at a final value in 1..9, which it then `puts`.

The leading 0 (in `0$argv`) is required just in case the question mark comes first in the input; a leading plus sign in the transformed sequence is not a problem for `expr`.

---
Tags: code-golf, math, arithmetic
---


title: Pairs with Sum divisible by 5

text:
# Question
Title: Pairs with Sum divisible by 5
You will be given two integers \\$M\\$ and \\$N\\$. Find the number of pairs \\$(x,y)\\$ such that \\$1 \le x \le M\\$, \\$1 \le y \le N\\$ and \\$(x+y)\bmod5 = 0\\$.

For example, if \\$M = 6\\$ and \\$N = 12\\$, pairs which satisfies such conditions are, \\$(1,4), (4,1), (1,9), (2,3), (2,8), (3,2), (3,7), (3,12), (4,6), (6,4), (4,11), (5,5), (5,10), (6,9)\\$

Total \\$14\\$.

### Sample

```
Input : 6 12
Output: 14

Input : 11 14
Output: 31

Input : 553 29
Output: 3208

Input : 2 2
Output: 0

Input : 752486 871672
Output: 131184195318

```

This is a code-golf challenge so code with lowest bytes wins!

### Update

**Jonathan Allan's** solution has the smallest code size, **5 bytes**. However, it doesn't produce an answer for the last given test.

I have decided to go with the next answer with the shortest size that produces the correct answer for the largest test, there is a tie between two golfers who competed neck-to-neck.

I proudly present the winners of this challenge **Lyxal** and **Kevin Cruijssen** with only **7 bytes** code! Congratulations!

As many of you, I found **Arnauld's** answer most helpful in finding the correct solution. So, I am accepting Arnauld's answer.

Thank you, Golfers!

# Answer
# JavaScript (ES6), 29 bytes

Takes input as `(m)(n)`.

```
m=>g=n=>n&&(m+n%5)/5+g(n-1)|0

```

Try it online!

### How?

Let's consider a grid of width \\$m\\$ with 1-indexed coordinates and an `X` mark on each cell for which:

$$(x+y)\equiv 0\pmod 5$$

Here are the first few rows for \\$m=9\\$:

```
   | 1 2 3 4 5 6 7 8 9
---+-------------------
 1 | - - - X - - - - X
 2 | - - X - - - - X -
 3 | - X - - - - X - -
 4 | X - - - - X - - -
 5 | - - - - X - - - -
 6 | - - - X - - - - X
 7 | - - X - - - - X -

```

Computing \\$m+(y\bmod5)\\$ is equivalent to left-padding each row in such a way that all `X` marks are vertically aligned and appear on columns whose index is a multiple of \\$5\\$.

With such a configuration, the number of marks is directly given by \\$\lfloor{L\_y/5}\rfloor\\$, where \\$L\_y\\$ is the updated length of the \\$y\\$-th row.

```
 y | y%5 |         padded row         | length | // 5
---+-----+----------------------------+--------+------
 1 |  1  |  + - - - X - - - - X       |   10   |   2
 2 |  2  |  + + - - X - - - - X -     |   11   |   2
 3 |  3  |  + + + - X - - - - X - -   |   12   |   2
 4 |  4  |  + + + + X - - - - X - - - |   13   |   2
 5 |  0  |  - - - - X - - - -         |    9   |   1
 6 |  1  |  + - - - X - - - - X       |   10   |   2
 7 |  2  |  + + - - X - - - - X -     |   11   |   2
---+-----+----------^---------^-------+--------+------
         |  0 0 0 0 **0** 0 0 0 0 **1** 1 1 1 |
         |  1 2 3 4 **5** 6 7 8 9 **0** 1 2 3 |
```

We use this method to recursively compute the number of marks on each row.
> 11 votes

# Answer
# Python 2, 32 bytes

```
lambda m,n:(m*n+abs(m%5-~n%5))/5

```

Try it online!

Adapts an idea from Arnauld. We estimate that \\$1/5\\$ of the \\$mn\\$ pairs will satisfy the mod-5 condition. Th actual value may be one higher depending on the mod-5 values of \\$m\\$ and \\$n\\$, and we bump up \\$mn\\$ a bit so that these make it pass the next multiple of 5.

---

**34 bytes**

```
lambda m,n:m*n/5+(0<-m%5*(-n%5)<5)

```

Try it online!

**34 bytes**

```
lambda m,n:m*n/5+(m*n%5+m%5+n%5)/9

```

Try it online!

**36 bytes**

```
lambda m,n:m*n/5+((5-m%5)*(5-n%5)<5)

```

Try it online!

**36 bytes**

```
lambda m,n:m*n/5+(abs(m%5+n%5*1j)>4)

```

Try it online!

**36 bytes**

```
lambda m,n:m*n/5+(m%5*5/4+n%5*5/4>5)

```

Try it online!

**36 bytes**

```
lambda m,n:m*n/5+(m%5+n%5+m*n%5/4>5)

```

Try it online!
> 13 votes

# Answer
# Jelly, 5 bytes

```
p§5ḍS

```

**Try it online!**

### How?

```
p§5ḍS - Link: positive integer, M; positive integer N
p     - (implicit [1..M]) Cartesian product (implicit [1..N])
 §    - sums
  5ḍ  - five divides? (vectorises)
    S - sum

```
> 6 votes

# Answer
# , 20 bytes

```
1#.[+/\0=5|1}.1+i.@+

```

Try it online!

The standard `O(m*n)` cartesian product solution saves 3 bytes `[:+/@,0=5|2++/&i.`, but I figured I'd try a different approach:

A solution using a sliding window.

I *think* J is able to optimize this approach automatically into `O(m+n)`... in any case, I get an out of memory error on the final test case on TIO with the cartesian product approach but not with this one

Let's take `6 f 12` as an example:

1. Generate the numbers 1 through 18 `1+i.@+`:

```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

```
2. Kill the first 1 `1}.`:

```
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

```
3. Turn it into a 0-1 list indicating which numbers are divisible by 5 `0=5|`

```
0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0

```
4. Create a sliding window of length of the left arg (either arg would work though), summing each piece of the window `[+/\`:

       1
  /`````````\ etc...
0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0
\_________/
      1

Final result: 1 1 1 2 1 1 1 1 2 1 1 1
</code></pre>
5. Sum of all those numbers `1#.`:

```
14

```
> 6 votes

# Answer
# Python 3, 50 bytes

```
lambda n,m:sum((i//n+i%n)%5==3for i in range(n*m))

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog Unicode), 11 bytes

Full program.

```
≢⍸0=5|+/¨⍳⎕

```

Try it online! (largest test case would work with 3TB RAM)

Reads quite literally as the problem specification:

count  where `0=` 0 equals `5|` the mod-5 of `+/` the sum of `¨` each of  all indices until  the input.
> 5 votes

# Answer
# MATL, 9 bytes

```
:i:!+5\~z

```

Try it online!

### How it works

```
:    % Implicit input: M. Range [1 2 ... M]
i:   % Input: N. Range [1 2 ... N]
!    % Transpose
+    % Add, element-wise with broadcast. Gives an N×M matrix
5    % Push 5
\    % Modulus, element-wise
~    % Negate
z    % Number of nonzeros. Implicit display

```
> 4 votes

# Answer
# Pyth, ~~12~~ 11 bytes

*-1 thanks to @Mukundan*

```
lf!%sT5*FSM

```

Try it online!

```
lf!%sT5*FSM
         SM    Map 1-indexed range to each input
       *F      Cartesian product of the two ranges
 f              Filter by:
    sT          - sum of elements..
  !%  5         - .. is divisible by 5
l               Take the length

```
> 4 votes

# Answer
# Python 2, 36 bytes

```
f=lambda m,n:m and(m%5+n)/5+f(m-1,n)

```

Try it online!

Use @Arnauld's formula, be sure to checkout and upvote his answer!

---

Original solution, using a longer formula:

# Python 2, ~~42~~ 41 bytes

*-1 byte thanks to @xnor!*

```
f=lambda m,n:m and(n%5>~m%5)+n/5+f(m-1,n)

```

Try it online!

For each number `i` between 1 to `m`, there are `(n%5+i%5>4)+n/5` numbers between 1 to n that can be paired with `i`.
> 4 votes

# Answer
# , 40 bytes

```
function(m,n)sum(!(rep(1:m,e=n)+1:n)%%5)

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~9~~ ~~8~~ 7 bytes

```
L5%+5÷O

```

Try it online!

A 100% port of @Arnauld's Javascript answer
> 4 votes

# Answer
# MathGolf, 7 bytes

```
╒5%+5/Σ

```

Port of *@Arnauld*'s JavaScript answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
╒        # Push a list in the range [1, (implicit) first input]
 5%      # Modulo-5 on each value in the list
   +     # Add the second (implicit) input to each
    5/   # Integer-divide each value by 5
      Σ  # And sum the list
         # (after which the entire stack joined together is output implicitly as result)

```
> 4 votes

# Answer
# K (ngn/k), 15 bytes

```
+//~5!+/:/1+!:'

```

Try it online!
> 3 votes

# Answer
# Japt, ~~11~~ 10 bytes

```
õ ï+Võ)èv5

```

Try it

```
õ ï+Võ)èv5     :Implicit input of integers U & V
õ              :Range [1,U]
  ï            :Cartesian product with
    Võ         :  Range [1,V]
   +           :  Reduce each pair by addition
      )        :End Cartesian product
       è       :Count the elements
        v5     :  Divisible by 5

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 56 bytes

```
Length@Solve[1<=x<=#&&1<=y<=#2&&Mod[x+y,5]==0,Integers]&

```

Try it online!
> 2 votes

# Answer
# perl -M5.010 -al, 49 bytes

```
for(1..$_){for$y(1..$F[1]){($_+$y)%5||$c++}}say$c

```

Try it online!

This is a pretty stupid, "iterate over all pairs, count the ones where sum mod 5 equals zero", solution. There's a nicer formula, but I couldn't (yet) reduce that down enough. It will take a very long time to calculate the answer to (752486, 871672), but there was no time limit stated.

The TIO link has a `$c = 0;` in the header. This isn't needed for a single line solution; it's only there to make it work with multiple inputs (and as such, TIO won't count those bytes).
> 2 votes

# Answer
# Charcoal, ~~16~~ 12 bytes

```
ＩΣ÷⁺﹪…·¹Ｎ⁵Ｎ⁵

```

Try it online! Link is to verbose version of code. Port of @KevinCruijssen's answer, although that's apparently a port of @Arnauld's answer. Explanation:

```
     …·        Inclusive range from
       ¹        Literal `1` to
        Ｎ       First input number
    ﹪           Vectorised Modulo
         ⁵      Literal `5`
   ⁺            Vectorised Plus
          Ｎ     Second input number
  ÷             Vectorised Integer divide by
           ⁵    Literal `5`
 Σ              Take the sum
Ｉ               Cast to string
                Implicitly print

```

Previous 16-byte brute force answer:

```
ＮθＩ№⭆Ｎ⭆θ﹪⁺²⁺ιλ⁵0

```

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

```
Ｎθ

```

Input `M`.

```
⭆Ｎ⭆θ

```

Input `N` and loop over `N` and `M`, casting the result to a string.

```
﹪⁺²⁺ιλ⁵

```

Take the sum modulo 5, adjusted for 1-indexing (sigh).

```
Ｉ№...0

```

Count the `0`s in the result.
> 2 votes

# Answer
# C (gcc), 36 bytes

```
f(n,m){n=m*n/5+((5-m%5)*(5-n%5)<5);}

```

Try it online!

A port of one of xnor's formulas.
> 2 votes

# Answer
# Erlang (escript), 69 bytes

Posting before I run out of time.

```
f(X,Y)->[[A,B]||A<-lists:seq(1,X),B<-lists:seq(1,Y),((A+B)rem 5)==0].

```

Try it online!
> 2 votes

# Answer
# Vyxal `s`, 6 bytes

```
ɾ5%+5ḭ

```

Try it Online!
> 2 votes

---
Tags: code-golf, math
---


title: Encode the backwards alphabet cipher

text:
# Question
Title: Encode the backwards alphabet cipher
Given a string of text that contains lowercase letters, encode it as follows: (I will be using `abcdef`)

* First, encode the alphabet cipher, but this time, 0-indexed. `000102030405`
* Reverse it. `504030201000`
* Loop through the string.
    + If the next two digits together are 25 or smaller, encode those two numbers. `5` `04` `03` `02` `01` `00` `0`
    + Otherwise, encode one number. `f` `e` `d` `c` `b` `a` `a`
* Join. `fedcbaa`

## Test cases

```
abcdef                          fedcbaa
abcdefghijklmnopqrstuvwxyz      fyxwvucjsrqponmlktihgfedcbaa
helloworld                      dbromylloha
ppcg                            gcfpb
codegolf                        fboqedema
programmingpuzzlesandcodegolf   fboqedemddkiobpzuzqdscmkhqerpb

```

Encoder (not golfed)

Remember, this is , so the code with the fewest bytes wins.

# Answer
> 2 votes
# JavaScript, ~~126~~ 125 bytes

```
s=>[...s.replace(/./g,c=>(parseInt(c,36)+90+'').slice(1))].reverse().join``.replace(/2[0-5]|[01]?./g,c=>(+c+10).toString(36))

```

Try it online!

# Answer
> 1 votes
# Perl, 73 + 2 = 75 bytes

Run with the `-lp` flag

```
s/./sprintf"%02d",-97+ord$&/eg;$_=reverse;s/2[0-5]|[01]?[0-9]/chr$&+97/eg

```

# Answer
> 1 votes
# Haskell, 107 bytes

```
g.reverse.(>>=tail.show.(+3).fromEnum)
g(a:b:c)|r<-read[a,b],r<26=['a'..]!!r:g c
g(a:b)=[a..]!!49:g b
g e=e

```

Try it online!

# Answer
> 0 votes
# 05AB1E, ~~31~~ 26 bytes

-5 bytes after taking a look at Lynn's Haskell answer.

```
Ç3+€¦JR[Ð2£₂‹>DŠ£Aè?.$DõQ#

```

Try it online!

```
Ç                     # codepoints of the input
 3+                   # add 3 to each (a->100, b->101, ...)
   €¦                 # remove the leading "1" from each number/string
     J                # join into a single string
      R               # and reverse the string
                                                                          STACK
[                     # infinite loop
 Ð                    # push 2 copies of the current remaining string s   s, s, s
  2£                  # take the first two chars of s                     s[:2], s, s
    ₂‹                # are they (as a number) less than 26 (0 or 1)      s[:2]<26, s, s
      >D              # add 1 and duplicate the result                    (s[:2]<26)+1, (s[:2]<26)+1, s, s
        Š             # rotate the top three items on the stack           (s[:2]<26)+1, s, (s[:2]<26)+1, s
         £            # take the first or two first characters from s     s[:(s[:2]<26)+1], (s[:2]<26)+1, s
          Aè          # index with those into the alphabet
            ?         # and print the result without a trailing newline
             .$       # remove the characters from s                      s[(s[:2]<26)+1:]
               DõQ#   # if s is now empty, exit the loop

```

---
Tags: code-golf, alphabet, cipher
---


# Question
Title: Packing Cuboid Boxes into the Shortest Stretchy Truck
You are a package handler for Big CompanyTM and your job is to load boxes into a truck. These are special, stretchy trucks: their length can be adjusted at will. But stretching trucks are expensive, so keep the truck lengths as short as possible!

# The Challenge

Write a full program or function that, when given the truck's height and width, and a list of cuboid boxes, outputs the minimum truck length for that sequence.

# Input

Your program has 2 inputs:

* The truck's height and width: a 2-tuple of positive integers
* The boxes to pack: a list of 3-tuples of positive integers

Each box is represented as a 3-tuple of numbers, representing their height, width, and length. It is guaranteed that boxes will be smaller than or the same size as the height and width of the truck.

You can freely rotate the boxes any number of times in 90-degree intervals. You can freely reorder the list of boxes.

You can freely rotate the truck around its length axis, i.e. a `(3,5)` truck is the same as a `(5,3)` truck.

# Output

Your program must output the *minimum* length of the truck needed to pack all of the boxes.

# Additional Rules

# Test Cases

(truck h, w) [(box h, w, l)...] -> truck length
(1,1) [(1,1,1)] -> 1
    (a single box)

(1,1) [(1,1,1) (1,1,1)] -> 2
    (a line of two 1x1x1 boxes)

(2,1) [(1,1,1) (1,1,1)] -> 1
    (two boxes stacked)

(1,2) [(1,1,1) (1,1,1)] -> 1
    (two boxes on the floor, next to each other)

(5,7) [(3,3,5) (1,1,1) (1,2,2)] -> 3
    (3x3x5 box is rotated such that it is parallel long-side-wise on the floor)

(5,7) [(5,3,5) (5,7,1) (5,2,2) (5,2,2)] -> 5
    (the 5x7x1 box on the back wall, the 5x2x2 boxes next to each other)

(4,4) [(3,2,5) (2,2,3) (2,2,4) (2,2,6)] -> 7
    (3x2x5 forces 2x2x3 and 2x2x4 to be length-wise adjacent)

(5,5) [(1,1,1) (2,2,2) (3,3,3) (4,4,4) (5,5,5)] -> 12
    (3x3x3 4x4x4 5x5x5 boxes adjacent, 1x1x1 and 2x2x2 crammed into empty space)

(5,5) [(1,1,1) (2,2,2) (3,3,3) (4,4,4) (5,5,5) (1,8,5)] -> 13
    (same arrangement as above, but 1x8x5 is squeezed between the wall and 4x4x4)
```
</code></pre>

# Answer
# Ruby, ~~292...~~ 228 bytes

```
->t,b{1.step.find{|l|[p].product(*b.map{|c|c.permutation.flat_map{|x,y,z|[*x..t[0]].product([*y..t[1]],[*z..l]).map{|i,j,k|[i-x...i,j-y...j,k-z...k]}}}).any?{|c|c.combination(2).none?{|a,b|a&.zip(b)&.all?{|x,y|[*x]&[*y]!=[]}}}}}

```

Try it online!

Probably still a lot left to optimize.

Can get the 6th test case on TIO in 17 seconds by adding a `uniq` after `permutation`. No way to get more than that.

### Explanation:

Brute force approach, pure and simple. Start with length 1, rotate all the boxes, and try all the possible translations. If there is no way to fit them, increase length and try again.
> 9 votes

# Answer
# Jelly, 44 bytes

```
_⁹żAƑƇŻ€,Œp€+þ@/ʋ/€Ẏ
Œ!€⁹,1W;"çⱮ/pẎ€QƑƇɗ/ʋ1#

```

Try it online!

A dyadic pair of links taking a list of boxes as the left argument and the truck’s first two dimensions as the right argument. Returns the result as an integer. Very inefficient as the boxes and truck get bigger and do times out on TIO even on the fifth test case.

## Explanation

Takes three truck dimensions on the left and a list of permuted boxes on the right. Returns a list of lists of coordinates for all possible translated and rotated versions of that box

```
_⁹                    | Subtract the permuted boxes from the truck
  ż                   | Zip each with the relevant permuation
   AƑƇ                | Keep only those that are non-negative (by checking whether the numbers are changed when absoluted)
                ʋ/€   | For each of the remaining ones, reduce using the following:
      Ż€              | - For each of the (truck-box) dimensions, generate a list from zero to that number
        ,             | - Pair with the box dimensions
         Œp€          | - Cartesian products of each
            +þ@/      | - Reduce using outer addition (generates a list of lists of coordinates for each cell of the translations of that permuation of the box)
                   Ẏ  | Tighten

```

```
Œ!€                     | Permutations of each box’s dimensions
   ⁹,                   | Pair truck dimensions with this (call this y)
     1              ʋ1# | Starting with 1, find the first integer x which satisfies the following, using y as the right argument:
      W;"               | - Wrap and concatenate zipped; effectively prepends x to the first member of y (the truck’s two dimensions)
         çⱮ/            | - Call the helper link with the three truck dimensions on the left for each box’s permutations on the right
                  ɗ/    | - Reduce the results of the helper link with the following:
            p           |   - Cartesian product
             Ẏ€         |   - Tighten (concatenate outer lists)
               QƑƇ      |   - Check whether unchanged on uniquifying (i.e. are there any duplicates?)

```
> 3 votes

---
Tags: code-golf, packing
---