title: !I!n!s!e!r!t! !i!n!b!e!t!w!e!e!n!

text:
# Question
Title: !I!n!s!e!r!t! !i!n!b!e!t!w!e!e!n!
Posted from here.

This challenge is highly "distilled" from this question. Special thanks to @Akababa!

In this task, you should insert an exclamation mark at the start of the string and after every character.

## Rules

* There will always be a non-empty-string input. The input will not contain tabs either. You can assume that the input only contain non-extended ASCII printable characters and newlines.
* The input will not contain trailing newlines as long as your language can't detect a newline.
* This is a contest; the shortest answer should win.

## Examples

* 4 newlines result in 5 newline-delimited exclamation marks. It is very hard to put this as a Markdown text, so this is stated instead.

```
1 2 3 4 5 6
129591 129012 129127 129582

0

```

Outputs

```
!1! !2! !3! !4! !5! !6!
!1!2!9!5!9!1! !1!2!9!0!1!2! !1!2!9!1!2!7! !1!2!9!5!8!2!
!
!0!

```

```
asd afjoK ak:e
kPrLd
    fOJOE;
    KFO
KFkepjgop sgpaoj   faj

```

Outputs

```
!a!s!d! !a!f!j!o!K! !a!k!:!e!
!k!P!r!L!d!
! ! ! ! !f!O!J!O!E!;!
! ! ! ! !K!F!O!
!K!F!k!e!p!j!g!o!p! !s!g!p!a!o!j! ! ! !f!a!j!

```

A base test case with only one character:

```
a

```

Outputs

```
!a!

```

(Auto-completion! Just kidding, there is no such thing.) Contains exclamation marks:

```
!!
!!
!!
!!
!!

```

Outputs:

```
!!!!!
!!!!!
!!!!!
!!!!!
!!!!!

```

# Answer
# QuadR, 1 byte

Thanks to A\__ for halving the byte count!

```
!

```

Try it online!

Replaces nothing with `!`
> 40 votes

# Answer
# Python 3, 26 bytes

```
lambda s:s.replace('','!')

```

Try it online!
> 16 votes

# Answer
# Retina 0.8.2, 2 bytes

```

!

```

Try it online! At last, a challenge where Retina has a built-in!
> 13 votes

# Answer
# Python 3, 27 bytes

```
lambda s:f"!{'!'.join(s)}!"

```

Try it online!

Honestly, I hope someone can show me a cool way to do this with a smaller byte count.
> 13 votes

# Answer
# Haskell, 18 bytes

```
('!':).(>>=(:"!"))

```

-1 byte thanks to @nimi

Try it online!
> 12 votes

# Answer
# Python 2, 27 bytes

```
lambda s:'!%s!'%'!'.join(s)

```

**Try it online!**
> 12 votes

# Answer
# brainfuck, ~~24~~ 22 bytes

-2 bytes thanks to JoKing.

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

```

Try it online!
> 11 votes

# Answer
# JavaScript (ES6), 19 bytes

Takes input as an array of characters.

```
s=>`!${s.join`!`}!`

```

Try it online!

---

# JavaScript (ES6),  ~~23~~  20 bytes

*Saved 3 bytes thanks to @ShieruAsakoto*

Takes input as a string.

```
s=>[,...s,,].join`!`

```

Try it online!

---

# JavaScript (ES6), 22 bytes

*Suggested by @tjjfvi*

Takes input as a string.

```
s=>s.replace(/|/g,"!")

```

Try it online!
> 9 votes

# Answer
# Labyrinth,  ~~19 11 10~~  9 bytes

```
33
..
",@

```

**Try it online!**

### How?

We enter the Labyrinth at the top-left facing right with an infinite stack of zeros...

```
                         I / O    stack
                                  0,0,0,...
3 - pop * 10 + 3                  3,0,0,0,...
  - 2 neighbours, forward
3 - pop * 10 + 3                  33,0,0,0,...
  - 2 neighbours, forward
. - pop & print chr          !    0,0,0,...
  - T junction from the side
  -   TOS==0, forward
, - read chr or -1       L        76,0,0,0,...   or   -1,0,0,0
  - T junction from the base
  -   if TOS > 0 right:
" -     no-op                     76,0,0,0,...
  -     2 neighbours, forward
. -     pop & print chr      L    0,0,0,...
  -     T junction from the side
  -       TOS==0, forward
3 -       ...back to the start
  -   elif TOS == -1 left:
@ -     exit                                          we're out!

  * right, but on the first occasion (from above) we hit the wall and turn
    around, so that's like a left

```

Luckily we don't need to handle un-printables, otherwise the first zero-byte would turn us around at `,` and play havoc.
> 9 votes

# Answer
# Pepe, 47 bytes

```
REREEeRErEErREeeEeeeeEREEeeREEeereeREEEEeeEReee

```

Try it online!

**Explanation:**

```
REREEeRE # Push 0,then input (str),then 0 -> (R)
         # The zeroes are pushed to correct the inserting
rEE # Begin loop labelled 0 -> (r)
  rREeeEeeeeE # Push "!" -> (R)
              # r flag inserts it instead of pushing
  REEeeREEee # Move pointer pos 2 steps forward -> (R)
ree # Loop while (R) != 0
REEEEeeE # Remove characters of (R) that are in stack of (r)
         # Removes the 0 in (R)
Reee # Output (R)

```
> 7 votes

# Answer
# , 25 bytes

```
function(x)gsub("","!",x)

```

Try it online!

A function accepting and returning a character vector.
> 7 votes

# Answer
# 8086 machine code, .COM format (MS-DOS 2+), 32 bytes

(-1 depending on emulator: see below)

For best results redirect standard input from a file, as typing gives odd-looking output due to no buffering; also, newlines look a little weird because they are stored as `CR LF`, and the `CR` part messes up the output.

This program behaves fine in an actual MS-DOS emulation (e.g. PCjs) but DOSBox seemed to have issues with Ctrl+Z EOF (see comments in the assembly listing), so *DON'T* try to enter input using the console in DOSBox unless you add the extra check!

```
BB 01 00 53 59 BA 0B 01 B4 40 CD 21 4A 4B B4 3F CD 21 85 C0 74 09 B4 40 43 41 CD 21 49 EB EE C3

```

Some interesting bits:

* I saved some data space by reusing memory that had already been executed (the `21H` in `INT 21H` happens to be `!`)
* I was *almost* able to use an interesting trick that I found on the page "The Hidden Power of BCD Instructions" which would have allowed me to use `AAA` instead of a standard `TEST` to compare `AL` to 0, saving one byte. Unfortunately, this is not fully documented so I couldn't rely on it: for example, PCjs doesn't adjust anything but the carry and auxiliary carry flags. :-(

Assembly code (TASM ideal mode):

```
IDEAL
MODEL   TINY

CODESEG
ORG 100H

;; DOSBox (tested with 0.74-2) didn't seem to handle Ctrl-Z as EOF
;; so uncomment the ";;" lines to run it there.
MAIN:
    MOV     BX,1
    PUSH    BX
    POP     CX
    MOV     DX,OFFSET MAIN_1+1  ; The 21H in INT 21H
    MOV     AH,40H
MAIN_1:
    INT     21H
    DEC     DX
    ;;PUSH  DX
    ;;POP   SI
IO_LOOP:
    DEC     BX
    MOV     AH,3FH
    INT     21H
    ;;; This should work on an non-emulated PC.
    ;;;AAA      ; AL=0?
    TEST    AX,AX
    JZ      DONE
    ;;CMP   [BYTE PTR SI],1AH
    ;;JZ    DONE
    MOV     AH,40H
    INC     BX
    INC     CX
    INT     21H
    DEC     CX
    JMP     IO_LOOP
DONE:
    RET
ENDS
END MAIN

```
> 7 votes

# Answer
# Jelly, 5 bytes

```
Ż”!ṁż

```

A full program accepting a string, which prints the result.

**Try it online!**

### How?

```
Ż”!ṁż - Main Link: list of characters, s   e.g. "abc"
 ”!   - character '!'                           '!'
   ṁ  - mould like:
Ż     -   s with a zero prepended              "!!!!"
    ż - zip together with s                    ["!a","!b","!c",'!']
      - implicit (smashing) print              !a!b!c!

```
> 5 votes

# Answer
# sed, 12 bytes

```
s/\b\|\B/!/g

```

Try it online!

*-3 bytes thanks to Cows Quack*
> 5 votes

# Answer
# 6502, 12 bytes (13 bytes if Apple II)

**6502**

The machine code assumes that a pair of zero page locations are connected to character input ($FE) and output (FF) hardware. Many 6502-based systems facilitate I/O in this fashion, albeit I/O address are usually not in zero page.

For simplicity, I used Py65, a 6502 microcomputer system simulator written in Python.

Here is a memory dump from Py65. You can load the following code anywhere in zero page such that it does not overlap $FE and $FF.

```
       PC  AC XR YR SP NV-BDIZC
6502: 0000 00 00 00 ff 00110010
.mem 0:b
0000:  a9  21  85  ff  a5  fe  f0  fc  85  ff  d0  f4

```

Running in a Windows command window, you can paste (Ctrl+V) any text you desire, or you can simply type. If typing, press Ctrl+J for a newline (same ASCII char). Press Ctrl+C to interrupt the processor and return to the Py65 command prompt.

Naturally, assembly code is easier to read.

```
       PC  AC XR YR SP NV-BDIZC
6502: 0000 00 00 00 ff 00110010
.d 00:0b
$0000  a9 21     LDA #$21
$0002  85 ff     STA $ff
$0004  a5 fe     LDA $fe
$0006  f0 fc     BEQ $0004
$0008  85 ff     STA $ff
$000a  d0 f4     BNE $0000

```

For clarity, here is the assembly code in CBA65 format.

```
; ASSEMBLE:
; cba65 bangit
;
; LOAD/RUN
; python3 py65/monitor.py -i 00fe -o 00ff -l bangit.bin
; goto 0000

        .FILES  BIN=256

; I/O LOCATIONS
GETC    .EQU    $FE             ; (1) MOVING PY65'S GETC TO ZP SHAVES 1 BYTE
PUTC    .EQU    $FF             ; (1) MOVING PY65'S PUTC TO ZP SHAVES 2 BYTES

        .ORG    $0000

VROOM   LDA     #'!'
        STA     PUTC
VROOM2  LDA     GETC
        BEQ     VROOM2
        STA     PUTC
        BNE     VROOM

        .END

```

**Apple II**

The code above assumes a null indicates there is no input, so continues polling until a non-null value is returned.

For comparison, the Apple I and Apple II signals availability of a new character by setting bit 7 of the keyboard I/O address, which then needs to be cleared after fetching the character. On those systems, character I/O usually is performed by calling system monitor routines instead of accessing the hardware directly.

By calling RDKEY ($FD0C) and COUT ($FDED), the Apple II equivalent of the above can be coded in 13 bytes, and is runnable anywhere in RAM. Here is the code I ran in an Apple //e emulator, a2ix on Android 9.

Pressing Return has the same effect as a newline.

```
*300L

0300-   A9 A1       LDA   #$A1
0302-   20 ED FD    JSR   $FDED
0305-   20 0C FD    JSR   $FD0C
0308-   20 ED FD    JSR   $FDED
030B-   F0 F3       BEQ   $0300

```

Did you notice that instead of the normal ASCII value #$21 for the exclamation point, #$A1 is used instead? That's because sending standard ASCII values to COUT causes them to be displayed in "inverse mode," black on white. Displaying ASCII in normal white on black requires adding #$80 to the character value in the accumulator before calling COUT. Because RDKEY returns characters with the hi-bit set, assembly programs generally cleared the bit of the character to obtain its ASCII value before using it.
> 5 votes

# Answer
# Zsh, ~~32~~ 23 bytes

```
<<<!${(j:!:)${(s::)1}}!

```

~~Try it online!~~  Try it online!

`(s::)` splits into characters, `(j:!:)` joins on `!`s.
> 4 votes

# Answer
# Perl 5 -p0, ~~17~~ 6 bytes

```
s,,!,g

```

Try it online!

My original answer was `-p` and `$_='!'.s,.,$&!,gr`. Thanks to @Nahuel Fouilleul for cutting 11 bytes and to @Grimy for the `-p0` tip.
> 4 votes

# Answer
# Perl 6, ~~16~~ 11 bytes

```
{S:g/<(/!/}

```

Try it online!

Replaces all zero width matches with exclamation marks. Null regexes are not allowed, so we use a capture marker to capture nothing instead
> 4 votes

# Answer
# Befunge-98 (PyFunge), 7 bytes

```
'!,#@~,

```

Try it online!
> 4 votes

# Answer
# MarioLANG, ~~95~~ ~~94~~ ~~90~~ ~~89~~ 69 bytes

```
++++++
======< >)
>+++++++",+[
=======<.==<
>+++++++!(.-
========#===

```

Try it online!

First time trying out MarioLANG, that was a lot of fun!

*Thanks to **Jo King** for -20 bytes*

**Explanation:**

So, as the name implies, MarioLANG is made to execute like a game of Super Mario Bros. It operates similarly to BF, with memory arranged in a tape of cells. There are operators to increment, decrement, print (as ascii or numeric) and read into the current memory cell, and operators to move left or right along the tape.

Mario (the instruction pointer) always begins in the top left cell of the program, with his intended direction of motion set to the right. If Mario does not have a floor-like object beneath him (=, ", or #), he will fall until he reaches a floor-like object. If Mario leaves the program space, the program ends due to Game Over :(

This specific program can basically be split into two halves: the setup, and the loop.

```
   Setup                          Loop
-----------------------------------------------
                       |
++++++                 |
======<                |          >)
>+++++++               |          ",+[
=======<               |          .==<
>+++++++               |          !(.-
========               |          #===

```

In the Setup section, we're simply incrementing the first memory cell until we reach 33 - the ASCII value for "!". Easy enough; if this can be golfed, it's purely a matter of shape. Mario starts from the top left, picks up 10 coins, starts falling when picking up the 11th, switches directions, then repeats. He picks up the last 11 coins without switching directions; he ends the setup section at the bottom-rightmost "+".

In the loop section, Mario starts by reaching an elevator. The "!" operator makes him cease motion, so that he remains on the elevator. On the way up, it prints the corresponding ASCII character to the current memory cell's value (this one is always 33, "!"), then switches to the next cell in memory. Mario reaches the top and sets his direction to the right. He falls, and reads a character from input as its ASCII value (or -1 if no character). We increment because the only measure of control in MarioLANG is to skip an instruction if the current memory cell has a value of 0. If it does, we skip changing Mario's direction, so he will walk right off of the next floor to his doom. If it does not, we set direction to left; walking left off of the floor below decrements the current cell back to its previous value, that value is printed, and we move back to the first memory cell before getting back on the elevator.

---

**Previous version (89 bytes):**

```
+++++++++++>,
==========@"+
+++++++++++)[
@==========.==<
+++++++++++!(.-
===========#===

```
> 4 votes

# Answer
# AWK, 11 bytes

```
gsub(a,"!")

```

Try it online!

This is similar to some other entries. It changes a null string to `!` globally, using `$0` as the default target, then prints the result since no other action is defined. Using `a` works since it's an undefined variable and is shorter than using `""` (which would do the same thing).
> 4 votes

# Answer
# APL (Dyalog Unicode), 11 bytes

```
(∊⊢⍪⍪¨)∘'!'

```

Try it online!

@Adám's golf to mine (see below).

```
{'!'⍪∊⍉↑⍵('!'⍴⍨≢⍵)}  ⍝ original
{'!'⍪∊⍵⍪¨('!'⍴⍨≢⍵)}  ⍝ concatenate each instead of transpose mix
{'!'⍪∊⍵⍪¨ '!'}       ⍝ each already handles many-to-one
{ ⍵ ⍪∊⍺⍪¨  ⍵ }∘'!'   ⍝ break out "!"
{∊⍵ ⍪ ⍺⍪¨  ⍵ }∘'!'   ⍝ defer flattening to later
(∊⊢ ⍪  ⍪¨    )∘'!'   ⍝ go tacit
(∊⊢⍪⍪¨)∘'!'          ⍝ remove spacing

```

# APL (Dyalog Unicode), 19 bytes

```
{'!'⍪∊⍉↑⍵('!'⍴⍨≢⍵)}

```

Try it online!

My first APL submission :P Loving this language. No idea why I need the parentheses after .

```
{'!'⍪∊⍉↑⍵('!'⍴⍨≢⍵)}
{                   } ⍝ Boilerplate
              ⍴⍨      ⍝ Repeat
           '!'        ⍝ Exclamation point
                 ≢⍵  ⍝ len(input) times
         ⍵(        )  ⍝ Wrap ^ into an array with the input
       ↑              ⍝ Matrixify
      ⍉               ⍝ Transpose
     ∊                ⍝ Flatten
    ⍪                  ⍝ Prepend
 '!'                  ⍝ An exclamation point

```
> 4 votes

# Answer
# Triangular, ~~15~~ 13 bytes

```
B\3;#*~.,</@<

```

Try it online!

*-2 bytes after remembering that Triangular has a conditional halt operator.*

I believe this is as short as it gets on this one. Triangular *does* have conditional direction-change operators, but they unfortunately work differently than the other conditionals. While all others check if ToS \<= 0, the direction-changing conditionals check ToS != 0. If this weren't the case, we would have 10 bytes in the form of `Bq3~#*/@<<`.

Ungolfed:

```
    B
   \ 3
  ; # *
 ~ . , <
/ @ <
----------------------------------------------------
B3*              - Push 11 and 3, then pop both and push their product.
    <,<          - Change directions 3 times (to save 2 bytes on last line)
        @/       - Print Top of Stack value as a character, do not pop
          ~;\    - Push a character from input to ToS. Halt if ToS <= 0. Change Direction.
              #  - Print ToS as a character and pop

```

---

**Previous Version (15 bytes):**

```
B.3\.*#).(/?~@<

```
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 28 bytes

```
s=>$"!{String.Join("!",s)}!"

```

Try it online!
> 3 votes

# Answer
# Java 8, 20 bytes

A lambda function from `String` to `String`.

```
s->s.replace("","!")

```

Try It Online
> 3 votes

# Answer
# 05AB1E, 4 bytes

```
€'!Ć

```

I/O as a list of characters.

Try it online.

**Explanation:**

```
€'!  '# Prepend a "!"-item before each character in the (implicit) input-list
   Ć  # Enclose (append the first character of the list at the end of it)
      # (after which the result is output implicitly)

```
> 3 votes

# Answer
# \>\<\>, ~~11~~ 6 bytes

```
"!"oio

```

Try it online!

Saved 5 bytes thanks to Jo King, suggesting exiting with an error. Previous version which does not exit with an error:

```
"!"oi:0(?;o

```

Try it online!
> 3 votes

# Answer
# Ruby, ~~17~~ 16 bytes

```
->s{s.gsub'',?!}

```

Try it online!

Thanks Value Ink for -1 byte
> 3 votes

# Answer
# SimpleTemplate, 23 bytes

This is a language I wrote, and it was supposed to be for templates, but well.

```
!{@eachargv.0}{@echo_}!

```

Should be almost self-explanatory, once you see the ungolfed code:

```
!{@each argv.0 as char} {@echo char}!{@/}

```

And an explanation:

* `!` \- Prints the literal `!` character
* `{@each argv.0 as char}` \- Loops through every character, with the value set to the variable `char` (**optional**, the default variable is `_`).
`argv.0` is the first parameter passed to the `render()` method of the compiler.
* `{@echo char}!` \- outputs the `char` variable and a literal `!` character.
For the golfed version, the default variable `_` is used instead.
* `{@/}` \- closes the loop (**optional**)

---

Pure **SimpleTemplate** solution:

```
{@fn x}!{@eachargv.0}{@echo_}!{@/}{@/}

```

Creates a function `x` that outputs the same result.

You can use it like this:

```
{@call x "this is an example"}

```

You can try all of this on: http://sandbox.onlinephpfunctions.com/code/f6baff8d411fc8227ece81eccf05b6e7d3586bfa

On the line 908, you can use the variables `$golfed`, `$ungolfed` and `$fn` to test all the versions.

---

---

However, if it is allowed to use a character array, the code is simplified (20 bytes):

```
!{@echoj"!" argv.0}!

```

And ungolfed:

```
!{@echo separator "!" argv.0}!

```

Basically, outputs all items in the array, joined by `"!"`, surrounded by literal `!`.
Due to limitations in the compiler class, the space is mandatory (in the golfed version).

This code is also extremelly harder to use in pure **SimpleTemplate** (using the function as example):

```
{@fn x}!{@echoj"!" argv.0}!{@/}

{@// alternative: @call str_split into a "a char array"}
{@set a "a", " ", "c", "h", "a", "r", " ", "a", "r", "r", "a", "y"}

{@call x a}

```

The `@call` can call a function that exists in PHP, which means that it isn't a pure **SimpleTemplate** solution.
> 3 votes

# Answer
# Bash, 36 bytes

```
while read -n1 c;do printf \!$c;done

```

Try it online!

This counts on the newline terminating the input for the last ! mark.
> 3 votes

# Answer
# VBA, ~~75 bytes~~ 72 bytes

72 bytes as a sub that outputs to the immediate window (thanks @taylorscott)

```
Sub s(x):Debug.?"!";:For i=1To Len(x):Debug.?Mid(x,i,1)"!";:Next:End Sub

```

75 bytes as a function that returns the formatted string.

```
Function t(x):t="!":For i=1To Len(x):t=t &Mid(x,i,1) &"!":Next:End Function

```

Which expands to and is readable as

```
Public Function t(x)
    t = "!"
    For i = 1 To Len(x)
        t = t & Mid(x, i, 1) & "!"
    Next
End Function

```

Test cases

```
Public Sub test_golf()

    x = "1 2 3 4 5 6" & vbCr & "129591 129012 129127 129582" & vbCr & vbCr & "0"
    'x = "a"
    'x = "!!" & vbCr & "!!" & vbCr & "!!" & vbCr & "!!" & vbCr & "!!"

    Debug.Print x
    s(x)              ' to call the sub
    Debug.Print t(x)  ' to call the function

End Sub

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~26~~ 16 bytes

```
"!"<>#&/@#<>"!"&

```

Try it online!

Input a list of characters. Returns a string.
> 3 votes

# Answer
# Kotlin, 50 bytes

```
fun f(s:String)=s.map{"!$it"}.joinToString("")+"!"

```

Try it online!

This is my first participation on this site, thought I would try a challenge with my new favourite language.
> 3 votes

# Answer
# MAWP, 18 bytes

```
%|092M3W!;~[;~!;~]

```

**Dion's solution.**

Try it!

### Older solution(19 bytes):

```
%|0~[65W3M;;]65W3M;

```

Try it!
> 3 votes

# Answer
# Hexagony, 11 bytes

```
$>P...@1;,<

```

Try it online!

```
  $ > P
 . . . @
1 ; , < .
 . . . .
  . . .

```
* `P1` in place of `33` so that it resets the memory.
* MP is stationary

# (old) Hexagony, 17 bytes

```
{33...@;",<./{;/>

```

Try it online!

```
  { 3 3
 . . . @
; " , < .
 / { ; /
  > . .

```

`{33` Puts an ! in left memory

`;"` Prints ! at the start and sets back mem

`,` Gets the next byte of input, `<` sends the IP U-R if null (which terminates it with `@`), D-R else

`/{;/` Reflects IP, prints current byte, and sets it to the next line

`>` Redirects the IP to the start of the loop
> 3 votes

# Answer
# Vyxal, 4 bytes

```
¤\!V

```

```
 ¤\!V - Full program
-------
 ¤    - Push empty string to the stack
  \!  - Push exclamation mark to the stack, better than `!`
    V - take implicit input and replace the empty
        string with the exclamation point

```

For an empty input, it will produce `!0!` because it considers the empty input 0, but I don't believe this can be fixed since taking input plainly returns 0 for "".

Try it Online!
> 3 votes

# Answer
# Japt, 4 bytes

```
rP'!

```

Try it

# Japt `-P`, 7 bytes

Unfortunately `!` is a reserved character, necessitating the quotation marks.

```
ï'! i'!

```

Try it

Not much to explain: `ï` is Cartesian product and `i` prepends.
> 2 votes

# Answer
# 05AB1E, 6 bytes

-1 thanks to Kevin Cruijssen. Takes input as a list of characters.

```
õ.ø'!ý

```

Try it online! or Try it online! (with input as a string)
> 2 votes

# Answer
# Gema, 11 characters

```
\A=\!
?=?\!

```

Unfortunately `!` starts a comment in Gema, so must be escaped.

Sample run:

```
bash-5.0$ echo -ne '1 2 3 4 5 6\n129591 129012 129127 129582\n\n0' | gema '\A=\!;?=?\!'
!1! !2! !3! !4! !5! !6!
!1!2!9!5!9!1! !1!2!9!0!1!2! !1!2!9!1!2!7! !1!2!9!5!8!2!
!
!0!

```

Try it online!
> 2 votes

# Answer
# Japt, 4 bytes

```
rP'!

```

Try it

```
r      Replace
 P     all empty strings "" with
  '!   An exclamation mark (If '!' wasn't a special character in Japt I could remove the quote)

```
> 2 votes

# Answer
# Perl 5 \+ `-p`, 11 bytes

```
s/^|.\K/!/g

```

Try it online!
> 2 votes

# Answer
# Pyth, 8 bytes

```
+\!s+R\!

```

Try it online!

---

```
     Code | Explanation
----------+-------------------------------------
+\!s+R\!  | Code
+\!s+R\!Q | with implicit variables filled
----------+-------------------------------------
     R  Q | For each d in input, replace d with:
    +R\!  |  d+"!"
   s      | Join results on empty string
+\!       | Add "!" to beginning
          | Print (implicit)

```
> 2 votes

# Answer
# **C (gcc), ~~69 62~~ 50 bytes**

Saved 12 bytes, thanks to ErikF's suggestion:

```
f(char*s){for(printf("!");*s;)printf("%c!",*s++);}

```

Try it online!
> 2 votes

# Answer
# , 12 bytes

```
'!',,@,.&'!'

```

Try it online!
> 2 votes

# Answer
# Aheui (esotope), 61 bytes

```
붖다따삭바사빠맣삭붛
밙봆＠뫃선차희져썬뻐

```

Try it online!

Nice small aheui code.
> 2 votes

# Answer
# Scala, 17 bytes

```
_.replace("","!")

```

Try it online!

-3b thanks to Jo King!
Thanks to Dr Y Wit for linking me to the fact that not enforcing typing is allowed, and for the working TIO link.
> 2 votes

# Answer
# Whitespace, 79 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S S S T S S T   N
_Push_9_tab][T  S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_END][S S S T    S S S S T   N
_Push_33_!][T   N
S S _Print_as_character][T  N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_END][S S S T  S S S S T   N
_Push_33_!][T   N
S S _Print_as_character]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace inputs one character at a time, the input should contain a trailing tab (`\t`) so it knows when to stop reading characters and the input is done.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start LOOP:
  Character c = STDIN as character
  If(c == '\t'):
    Call function END
  Print '!'
  Print c
  Go to next iteration of loop

function END:
  print '!'

```
> 2 votes

# Answer
# MathGolf, 6 bytes

```
É'!\'!

```

Try it online!

## Explanation

Nothing fancy here, just a loop

```
É        for each character do the next 3 operations
 '!      push single character "!"
   \     swap top elements
    '!   push single character "!"

```
> 2 votes

# Answer
# PHP (7.4), 31 bytes

Based on Petah's comment.

```
fn($s)=>preg_replace(__,'!',$s)

```

Try it online!

---

# PHP, 52 bytes

```
function($s){return'!'.join('!',str_split($s)).'!';}

```

Try it online!
> 2 votes

# Answer
# PHP, 75 bytes

Full program.

```
foreach(file('php://stdin')as$e)echo'!'.implode("!",str_split($e));echo"!";

```

Try it online!

# PHP, 100 bytes

```
foreach(explode("\n",file_get_contents('php://stdin'))as$e)echo'!'.implode("!",str_split($e))."!\n";

```

Try it online!

# PHP, 117 bytes

```
foreach(explode("\n",file_get_contents('php://stdin'))as$e){echo'!';foreach(str_split($e)as$c)echo $c."!";echo "\n";}

```

Try it online!
> 2 votes

# Answer
# Forth (gforth), 40 39 bytes

```
: f ." !"bounds do i 1 type ." !"loop ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  ." !"bounds \ print ! and place the ending address on the stack
  do          \ start a counted loop from start-addr to end-addr
    i         \ get address of current char
    1 type    \ print the char at the given address
    ." !"     \ print !
  loop        \ end the loop
;             \ end the word definition

```
> 2 votes

# Answer
# Emacs Lisp, 41 bytes

```
(while(or(insert"!")(not(forward-char))))

```

Assuming input is received as the contents of the current buffer
> 2 votes

# Answer
# C (gcc), ~~48~~ ~~45~~ 39 bytes

```
f(char*s){printf("!%.1s",s++)>1&&f(s);}

```

Try it online!

-3 thanks to ceilingcat
> 2 votes

# Answer
# Python 3, 26 bytes

```
lambda x:x.replace('','!')

```

Try it online!
> 2 votes

# Answer
# Keg, ~~9~~ 8 bytes

```
?⑷\!⑸\!^

```

Using a mapping approach really does help

Try it online!

## Answer History

### 9 bytes

```
?^(\!')\!

```

Pretty much a port of the MathGolf submission.

Try it online!
> 2 votes

# Answer
# PowerShell, 21 bytes

```
"$args"-replace"","!"

```

Try it online!

Boring regex `replace`ment is boring. ;-)
> 2 votes

# Answer
# Brachylog, 10 bytes

```
"!"w.∋w?w⊥

```

Try it online!

Takes input through the *output* variable, and unifies the input variable with `"!"`, printing the output.

```
"!"w          Print "!", which is the input variable.
    .∋w       Print an element of the output variable.
       ?w     Print the input variable again.
         ⊥    Fail.

```
> 2 votes

# Answer
# Brain-Flak, 54 bytes

```
(()){({}<>)((((()()()()){}){}){}())<>}<>{({}<>)<>}<>{}

```

Try it online!

**Code:**

```
(())                            push 1, so the loop runs at least one time
{                               while stack 1 isn't empty
    ({}<>)                      move letter to stack 2
    ((((()()()()){}){}){}())    push 33 (Exclamation Mark) on stack 2
    <>                          return to stack 1 for checking if the end is reached
}
<>{({}<>)<>}                    move everything from stack 2 back to stack 1 (otherwise the text would be reversed)
<>{}                            switch to stack 1 and delete leading 1

```
> 2 votes

# Answer
# Pushy, 9 bytes

```
L:33{;33"

```

Try it online!

```
L:   ;        \ len(input) times do:
  33          \    Append character 33 (exclamation mark)
    {         \    Cyclically shift the string left once
      33      \ Append character 33 again
        "     \ Print the result

```
> 2 votes

# Answer
# Javascript (27 bytes)

My first code golf, 27 bytes in Javascript. Could probably shave some more bytes off, but I'm not too sure.

```
f={x:s=>`!${s.join('!')}!`}

```

**Example Usage**

```
console.log(f.x('1 2 3 4 5'.split('')))
// Output: !1! !2! !3! !4! !5!

```
> 2 votes

# Answer
# 1+, ~~20~~ 19 bytes

```
1##11"+""*"**+;,;1#

```

1+ 19 vs 18 MAWP

Error-terminating because comparison is expensive.
> 2 votes

# Answer
# K (ngn/k), ~~13~~ 12 bytes

-1 byte from @ngn's savings

```
{x,/y,'x}"!"

```

Try it online!

Creates a function projection, with `x` fixed to `"!"`.

* `y,'x` pair-wise append an exclamation mark to each character in the input
* `x,/` flatten the list, using "!" as the seed (to prepend the leading "!")
> 2 votes

# Answer
# AWK, 11 bytes

```
gsub(_,"!")

```

```
 echo '
1 2 3 4 5 6
129591 129012 129127 129582

0
asd afjoK ak:e
kPrLd
    fOJOE;
    KFO
KFkepjgop sgpaoj   faj
!!
!!
!!
!!
!!' | awk 'gsub(_,"!")'

```

---

```
!1! !2! !3! !4! !5! !6!
!1!2!9!5!9!1! !1!2!9!0!1!2! !1!2!9!1!2!7! !1!2!9!5!8!2!
!
!0!
!a!s!d! !a!f!j!o!K! !a!k!:!e!
!k!P!r!L!d!
! ! ! ! !f!O!J!O!E!;!
! ! ! ! !K!F!O!
!K!F!k!e!p!j!g!o!p! !s!g!p!a!o!j! ! ! !f!a!j!
!!!!!
!!!!!
!!!!!
!!!!!
!!!!!

```
> 2 votes

# Answer
# Python, 30 Bytes

```
lambda x:'!%s!'%'!'.join([*x])

```

It feels like these methods were designed for the challenge!

## -1 from Jacob (now noodle man) by using ***the cursed `%`*** (Dun dun dun!)

## -3 from Glorfindel for using a starred method for conversion!

### **!T!r!y! !r!u!n!n!i!n!g! !i!t! !o!n!l!i!n!e!**
> 2 votes

# Answer
# Rockstar, 67 bytes

```
listen to S
while S
cut S
join S with "!"
say "!"+S+"!"
listen to S

```

Try it here (Code will need to be pasted in)
> 2 votes

# Answer
# Python 3, 29 Bytes

```
print('',*input(),'',sep="!")

```

Try It Online
> 2 votes

# Answer
# Charcoal, 6 bytes

```
⭆Ｓ⁺!ι!

```

Try it online! Link is to verbose version of code. Works on empty strings too. Input format is somewhat cumbersome due to Charcoal's lack of EOF. Works by preceding each character with a `!` and then suffixing a final `!` on the end. Alternative version, also 6 bytes:

```
⪫!!⪫Ｓ!

```

Try it online! Link is to verbose version of code. Works by joining the characters on `!` and then wrapping them in `!!`.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 94 bytes

```
I	I =INPUT	:F(END)
S	I LEN(1) . X REM . I	:F(O)
	O ='!' O X	:(S)
O	OUTPUT =O '!'
	O =	:(I)
END

```

Try it online!

Prints with an additional trailing newline (as SNOBOL always prints a line break). The way input is consumed, there is no way of distinguishing between a final line ending in `\n` or not.
> 1 votes

# Answer
# Stax, ~~6~~ 5 bytes

```
_z'!R

```

Run and debug it

Replace `""` with `"!"` using regex replacement. I don't exactly understand why this works.

*Edit:* Found it in the Ecma spec: 15.5.4.10

> If there is a match with an emptystring (in other words, if the value of *regexp*.**lastIndex** is left unchanged), increment *regexp*.**lastIndex** by 1.

**Old Stuff:**

I ~~would~~ have been able to get to 5 bytes ~~in either of two scenarios.~~

1. If input was provided in an escaped literal e.g. `"line1\nline2"`. But I opted against that for the sake of "usability".
2. If there was not a ~~bug~~ *feature* in stax's zip implementation when encountering empty strings/arrays.
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~49~~ ~~48~~ 42 bytes

```
#~StringSplit~""~StringRiffle~{a="!",a,a}&

```

Try it online!

-6 bytes thanks to @attinat
> 1 votes

# Answer
# C#, 142 bytes

```
public class P{public static void Main(string[]a){System.Console.Write("!");foreach(char c in a[0]){System.Console.Write(c.ToString()+"!");}}}

```
> 1 votes

# Answer
# Elvish, 32 bytes

```
use re;re:replace "" "!" (slurp)
```

Copy and paste into the Live Environment to try it out!
> 1 votes

# Answer
# C (gcc), 32 bytes

```
f(s){printf("!%s",s)-1&&f(s+4);}

```

Try it online!
> 1 votes

# Answer
# Ahead, 12 bytes

```
~irj!'~
@Wu<

```

Try it online!
> 1 votes

# Answer
# Lua, 31 bytes

```
print((io.read():gsub("","!")))

```
> 1 votes

# Answer
# Red, 47 bytes

```
func[s][parse s[insert"!"any[skip insert"!"]]s]

```

Try it online!
> 1 votes

# Answer
# Pip, 5 bytes

```
aJW'!

```

Try it online!

The `JW` builtin was made for challenges like this.
> 1 votes

# Answer
# Zsh, 12 bytes

```
<<<${1///!}!

```

Try it online!
> 1 votes

# Answer
# Branch, 11 bytes

```
33.,[.33.,]

```

Try it on the online Branch interpreter!

Put 33 on the tree and output (`!`). Then, grab input. Finally, while that value is not EOF, output it, output 33 (`!`), and grab input again.
> 1 votes

# Answer
# Vim, 13 bytes

```
:%s/\_./!&/g

```

Works by putting a `!` before every character, including newline characters. The TIO version doesn't work properly for the 4 newline testcase, but it does work in Vim.

Try it online!
> 1 votes

# Answer
# Subleq (8-bit), ~~12~~11 bytes

*-1 byte for removing last 0*

```
2 -1 33
-1 8 -1
8 -1 0
8 8

```

Subleq emulator

## Explanation

```
0:  2 -1 33 ' Output 2: (char(33)); 3rd argument is not used for output so use it for memory
3: -1  8 -1 ' Read input to 8:, exit if null
6:  8 -1  0 ' Output 8:
9:  8  8    ' 8: = 0 goto 0

```
> 1 votes

# Answer
# BRASCA, ~~14~~ 13 bytes

-1 byte thanks to RezNesX

```
,![$'!oo{]'!o

```

Try it online!

## Explanation

```
,               - Reverse stack
 ![$    {]      - Loop stack length:
    '!oo        -     Print "!" followed by the next letter
          '!o   - Print the last "!"

```
> 1 votes

# Answer
# Go, 105 bytes

```
import."regexp"
func f(s[]byte)[]byte{return append(MustCompile(`(?s).`).ReplaceAll(s,[]byte(`!$0`)),33)}

```

Attempt This Online!
> 1 votes

# Answer
# Excel, 44 bytes

```
="!"&CONCAT(MID(A1,SEQUENCE(LEN(A1)),1)&"!")

```
* `"!"` is just the first `!`.
* `CONCAT(MID(A1,SEQUENCE(LEN(A1)),1)&"!")`
    + `SEQUENCE(LEN(A1))` creates an array `1, 2, ... X` where `X` is the length of the input.
    + `MID(A1,SEQUENCE(~),1)` pulls the n<sup>th</sup> character from the input.
    + `MID(~)&"!"` adds `!` after every one of those characters.
    + `CONCAT(MID(~)&"!")` combines all those n<sup>th</sup> character + `!` into one string.

<sup>Note: The line breaks are there with or without Word Wrap turned on but it won't look right until you turn it on. The screenshot has Word Wrap turned on.</sup>
> 1 votes

# Answer
# Factor, <sup> ~~31~~ </sup> 28 bytes

```
[ 33 interleaved [I !${}!I]]

```

Attempt This Online!

* `33 interleaved` Insert an exclamation point between each character of the input.
* `[I !${}!I]` Interpolate the above string into the `${}`, adding exclamation points to the beginning and end, and print.
> 1 votes

# Answer
# BQN, 11 bytes

```
'!'⊸(⊣∾´∾¨)

```

Anonymous tacit function that takes and returns a string. Try it at BQN online!

### Explanation

```
'!'⊸(⊣∾´∾¨)
    (      )  Call the following function with the original argument on the right
'!'⊸          and '!' on the left:
         ∾¨     Concatenate each (prepends '!' to each character, resulting
                in a list of two-character strings)
       ∾´       Right-fold that list on concatenation
     ⊣          with a starting value of the left argument (i.e. '!')

```

---

A port of Sʨɠɠan's APL solution is also 11 bytes:

```
(∾⊢∾∾¨)⟜'!'

```

Try it!
> 1 votes

# Answer
# (,) ~~111~~ 91 Chars or \\$91\log\_{256}(3)\approx18.03\\$ Bytes

```
((),()()()()()()()())((),(())(())(())(())())(,,,(()()),(,(()(),((()()())),,(())))(()()),())

```

TIO
> 1 votes

# Answer
## C, 42 bytes

```
f(char *s){printf("!%c",*s);if(*s++)f(s);}

```

Essentially to not have to have two printf statments I have the printf run on the null byte of the string which prints the '!' but the null byte is ignored.

**Easier to read**

```
f(char *s){
  // Prints ! and char of string
  printf("!%c", *s);

  // If more string than recurse for next char
  if(*s != 0) f(s+1);
}

```
> 1 votes

# Answer
# Husk, ~~10~~ 8 bytes

<sup>*-2 bytes thanks to Razetime!*</sup>

```
`:'!ṁe'!

```

Try it online!
> 0 votes

# Answer
# x86-16 machine code, 8 bytes

```
00000000: b021 aaa4 aae2 fcc3                      .!......

```

Listing:

```
B0 21       MOV  AL, '!'        ; character to insert
AA          STOSB               ; write first ! to output string
        CLOOP:
A4          MOVSB               ; copy input char to output string
AA          STOSB               ; write ! to output string
E2 FC       LOOP CLOOP          ; loop until end of input
C3          RET                 ; return to caller

```

Callable function, input at `SI`, length in `CX`. Output to string at `DI`.

Test runs:
> 0 votes

# Answer
# Julia, <sup>~~21~~ ~~20~~</sup> 19 bytes

```
x->'!'join(x,!)*'!'

```

Try it online!
> 0 votes

# Answer
# Python 3, 80 bytes

```
s=list(input())
n=0
print(end="!")
for x in s:
    print(s[n],end="!")
    n=n+1

```

Try it online!
> 0 votes

# Answer
# ARM Thumb machine code, 12 bytes

```
21 22 08 c8 0c c1 00 2b fb d1 70 47

```

Assembly source:

```
    .syntax unified
    .arch armv7-a
    .thumb
    .thumb_func
    .globl insert_between
// input: r0: pointer to null terminated UTF-32LE string
//        r1: pointer to buffer
// output: null terminated UTF-32LE string at *r1
// C callable prototype:
//   void insert_between(const char32_t *in, char32_t *out);
insert_between:
    // Put '!' in a register for later
    movs   r2, #'!'
.Lloop:
    // Load char from pointer, advance pointer
    ldmia  r0!, {r3}                          @ tmp = *in++;
    // Store '!' then the char from the pointer.
    // The null terminator will be included,
    // which also adds the trailing '!'.
    stmia  r1!, {r2, r3}                      @ *out++ = '!', *out++ = tmp;
    // Loop if r3 wasn't a null terminator
    cmp    r3, #0
    bne    .Lloop
    // return
    bx     lr

```

Callable from C with the following prototype:

```
void insert_between(const char32_t *in, char32_t *out);

```

As with most of my Thumb string solutions, everything is null terminated UTF-32 thanks to `ldmia` and `stmia` being the only narrow instructions to load and advance a pointer.
> 0 votes

# Answer
# \>\<\> (Fish), 18 bytes

```
'!'orl0=?;o'!'o40.

```

Try it
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
""'!v

```

Attempt This Online!

## Thunno 2, 6 bytes

```
'!j'!ṛ

```

Attempt This Online!

#### Explanations

```
""'!v  # Implicit input
    v  # Replace...
""     # ...the empty string...
  '!   # ...with "!" in the input
       # Implicit output

```

```
'!j'!ṛ  # Implicit input
'!j     # Join by "!"
   '!ṛ  # Surround by "!"
        # Implicit output

```
> 0 votes

# Answer
# Rust, 25 bytes

```
|s:&str|s.replace("","!")

```

Attempt This Online!
> 0 votes

# Answer
# Marbles, 2087 bytes

An elegant 25 x 31 grid of 774 characters:

```
○══════════════════════╗
║○═══════════════════╗ ║
║║○════════════════╗ ║ ║
║║║○═════════════╗ ║ ║ ║
║║║║○══════════╗ ║ ║ ║ ║
║║║║║○═══════╗ ║ ║ ║ ║ ║
║║║║║║○════╗ ║ ║ ║ ║ ║ ║
║║║║║║║○═╗ ║ ║ ║ ║ ║ ║ ║
║║║║║║║║○╜○╜○╜○╜○╜○╜○╜○╜
║║║║║║║║ ┃ ║ ║ ║ ║ ┃ ║ ║
║║║║║║║║◆╢◆╢◆╢◆╢◆╢◆╢◆╢◆╢
║║║║║║║║ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃
║║║║║║║║◇╢◇╢◇╢◇╢◇╢◇╢◇╢◇╢
║║║║║║║║○╬═╬═╬═╬═╬═╬═╬╗║
║║║║║║║║║║╔╬╗║╔╬╗║╔╬╗║║║
║║║║║║║║╓╢╙╢╓╢╙╢╓╢╙╢╓╢╙╢
║║║║║║║║╚╬╝║╚╬╝║╚╬╝║╚╬╝║
║║║║║║║║○╜○╜○╜○╜○╜○╜○╜○╜
║║║║║║║║ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃
║║║║║║║║◇╜◇╜◇╜◇╜◇╜◇╜◇╜◇╜
║║║║║║║║◆╢◆╢◆╢◆╢◆╢◆╢◆╢◆╢
║║║║║║║║ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃
║║║║║║║║◇╢◇╢◇╢◇╢◇╢◇╢◇╢◇╢
║║║║║║║╚═╝ ║ ║ ║ ║ ║ ║ ║
║║║║║║╚════╝ ║ ║ ║ ║ ║ ║
║║║║║╚═══════╝ ║ ║ ║ ║ ║
║║║║╚══════════╝ ║ ║ ║ ║
║║║╚═════════════╝ ║ ║ ║
║║╚════════════════╝ ║ ║
║╚═══════════════════╝ ║
╚══════════════════════╝

```

Marbles is not available on tio.run yet but the test examples can be run using marbles.py:

```
± echo test | ./marbles.py exclamation.txt --quiet --no-display
!t!e!s!t!
!

```

Ungolfed version:

```
╔══════════════════════════════════════════════════╗
║  ╔════════════════════════════════════════════╗  ║
║  ║  ╔══════════════════════════════════════╗  ║  ║
║  ║  ║  ╔════════════════════════════════╗  ║  ║  ║
║  ║  ║  ║  ╔══════════════════════════╗  ║  ║  ║  ║
║  ║  ║  ║  ║  ╔════════════════════╗  ║  ║  ║  ║  ║
║  ║  ║  ║  ║  ║  ╔══════════════╗  ║  ║  ║  ║  ║  ║    ┓ 8 marbles representing a byte
║  ║  ║  ║  ║  ║  ║  ╔════════○  ○  ○  ○  ○  ○  ○  ○    ┛ This is the main variable
║  ║  ║  ║  ║  ║  ║  ║        ╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗  ┓
║  ║  ║  ║  ║  ║  ║  ║        ╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝  ┃
║  ║  ║  ║  ║  ║  ║  ║     ○══╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╗ ┃ Synchronization
║  ║  ║  ║  ║  ║  ║  ║     ║  ╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗║ ┃ Right-most marble exits first
║  ║  ║  ║  ║  ║  ║  ║     ║  ╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝║ ┃
║  ║  ║  ║  ║  ║  ║  ║     ╚══╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╝ ┛
║  ║  ║  ║  ║  ║  ║  ║        ╙○ ╙○ ╙○ ╙○ ╙○ ╙○ ╙○ ╙○   ┓ Set value to 0x21
║  ║  ║  ║  ║  ║  ║  ║        ║  ║  ┃  ║  ║  ║  ║  ┃    ┛ (the ascii character '!')
║  ║  ║  ║  ║  ║  ║  ║        ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆   ┓
║  ║  ║  ║  ║  ║  ║  ║        ┃  ┃  ┃  ┃  ┃  ┃  ┃  ┃    ┃ Write the byte to stdout
║  ║  ║  ║  ║  ║  ║  ║        ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇   ┃ LSB is on the right
║  ║  ║  ║  ║  ║  ║  ║        ┃  ┃  ┃  ┃  ┃  ┃  ┃  ┃    ┛
║  ║  ║  ║  ║  ║  ║  ║        ╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗  ┓
║  ║  ║  ║  ║  ║  ║  ║        ╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝  ┃
║  ║  ║  ║  ║  ║  ║  ║     ○══╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╗ ┃ Synchronization
║  ║  ║  ║  ║  ║  ║  ║     ║  ╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗╚═╗║ ┃ Right-most marble exits first
║  ║  ║  ║  ║  ║  ║  ║     ║  ╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝╔╤╝║ ┃
║  ║  ║  ║  ║  ║  ║  ║     ╚══╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╬╛═╝ ┛
║  ║  ║  ║  ║  ║  ║  ║        ╙○ ╙○ ╙○ ╙○ ╙○ ╙○ ╙○ ╙○   ┓ Read a byte from stdin
║  ║  ║  ║  ║  ║  ║  ║        ┃  ┃  ┃  ┃  ┃  ┃  ┃  ┃    ┃ LSB is on the right
║  ║  ║  ║  ║  ║  ║  ║        ╙◇ ╙◇ ╙◇ ╙◇ ╙◇ ╙◇ ╙◇ ╙◇   ┛
║  ║  ║  ║  ║  ║  ║  ║        ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆ ╟◆   ┓
║  ║  ║  ║  ║  ║  ║  ║        ┃  ┃  ┃  ┃  ┃  ┃  ┃  ┃    ┃ Write the byte to stdout
║  ║  ║  ║  ║  ║  ║  ║        ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇ ╟◇   ┃ LSB is on the right
║  ║  ║  ║  ║  ║  ║  ║        ┃  ┃  ┃  ┃  ┃  ┃  ┃  ┃    ┛
║  ║  ║  ║  ║  ║  ║  ╚════════╝  ║  ║  ║  ║  ║  ║  ║
║  ║  ║  ║  ║  ║  ╚══════════════╝  ║  ║  ║  ║  ║  ║
║  ║  ║  ║  ║  ╚════════════════════╝  ║  ║  ║  ║  ║
║  ║  ║  ║  ╚══════════════════════════╝  ║  ║  ║  ║
║  ║  ║  ╚════════════════════════════════╝  ║  ║  ║
║  ║  ╚══════════════════════════════════════╝  ║  ║
║  ╚════════════════════════════════════════════╝  ║
╚══════════════════════════════════════════════════╝

```

This is the first marbles submission ever :)
> 0 votes

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


title: Greatest Common Divisor

text:
# Question
Title: Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range `[0,255]`, whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard rules apply.

### Test Cases

```
0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101

```

# Answer
> 40 votes
# Retina, 16

```
^(.+)\1* \1+$
$1

```

This doesn't use Euclid's algorithm at all - instead it finds the GCD using regex matching groups.

Try it online. \- This example calculates GCD(8,12).

Input as 2 space-separated integers. Note that the I/O is in unary. If that is not acceptable, then we can do this:

# Retina, 30

```
\d+
$*
^(.+)\1* \1+$
$1
1+
$.&

```

Try it online.

As @MartinBüttner points out, this falls apart for large numbers (as is generally the case for anything unary). At very a minimum, an input of INT\_MAX will require allocation of a 2GB string.

# Answer
> 30 votes
## i386 (x86-32) machine code, 8 bytes (9B for unsigned)

+1B if we need to handle `b = 0` on input.

## amd64 (x86-64) machine code, 9 bytes (10B for unsigned, or ~~14B~~ 13B for 64b integers signed or unsigned)

## ~~10~~ 9B for unsigned on amd64 that breaks with either input = 0

---

Inputs are 32bit non-zero *signed* integers in `eax` and `ecx`. Output in `eax`.

```
## 32bit code, signed integers:  eax, ecx
08048420 <gcd0>:
 8048420:       99                      cdq               ; shorter than xor edx,edx
 8048421:       f7 f9                   idiv   ecx
 8048423:       92                      xchg   edx,eax    ; there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
 8048424:       91                      xchg   ecx,eax    ; eax = divisor(from ecx), ecx = remainder(from edx), edx = quotient(from eax) which we discard
    ; loop entry point if we need to handle ecx = 0
 8048425:       41                      inc    ecx        ; saves 1B vs. test/jnz in 32bit mode
 8048426:       e2 f8                   loop   8048420 <gcd0>
08048428 <gcd0_end>:
 ; 8B total
 ; result in eax: gcd(a,0) = a

```

This loop structure fails the test-case where `ecx = 0`. (`div` causes a `#DE` hardware execption on divide by zero. (On Linux, the kernel delivers a `SIGFPE` (floating point exception)). If the loop entry point was right before the `inc`, we'd avoid the problem. The x86-64 version can handle it for free, see below.

**Mike Shlanta's answer was the starting point for this**. My loop does the same thing as his, but for signed integers because `cdq` is one byter shorter than `xor edx,edx`. And yes, it does work correctly with one or both inputs negative. Mike's version will run faster and take less space in the uop cache (`xchg` is 3 uops on Intel CPUs, and `loop` is really slow on most CPUs), but this version wins at machine-code size.

I didn't notice at first that the question required **unsigned** 32bit. Going back to `xor edx,edx` instead of `cdq` would cost one byte. `div` is the same size as `idiv`, and everything else can stay the same (`xchg` for data movement and `inc/loop` still work.)

Interestingly, for 64bit operand-size (`rax` and `rcx`), signed and unsigned versions are the same size. The signed version needs a REX prefix for `cqo` (2B), but the unsigned version can still use 2B `xor edx,edx`.

In 64bit code, `inc ecx` is 2B: the single-byte `inc r32` and `dec r32` opcodes were repurposed as REX prefixes. `inc/loop` doesn't save any code-size in 64bit mode, so you might as well `test/jnz`. Operating on 64bit integers adds another one byte per instruction in REX prefixes, except for `loop` or `jnz`. It's possible for the remainder to have all zeros in the low 32b (e.g. `gcd((2^32), (2^32 + 1))`), so we need to test the whole rcx and can't save a byte with `test ecx,ecx`. However, the slower `jrcxz` insn is only 2B, **and we can put it at the top of the loop to handle `ecx=0` on entry**:

```
## 64bit code, unsigned 64 integers:  rax, rcx
0000000000400630 <gcd_u64>:
  400630:       e3 0b                   jrcxz  40063d <gcd_u64_end>   ; handles rcx=0 on input, and smaller than test rcx,rcx/jnz
  400632:       31 d2                   xor    edx,edx                ; same length as cqo
  400634:       48 f7 f1                div    rcx                      ; REX prefixes needed on three insns
  400637:       48 92                   xchg   rdx,rax
  400639:       48 91                   xchg   rcx,rax
  40063b:       eb f3                   jmp    400630 <gcd_u64>
000000000040063d <gcd_u64_end>:
## 0xD = 13 bytes of code
## result in rax: gcd(a,0) = a

```

---

Full runnable test program including a `main` that runs `printf("...", gcd(atoi(argv[1]), atoi(argv[2])) );` **source and asm output on the Godbolt Compiler Explorer**, for the 32 and 64b versions. Tested and working for 32bit (`-m32`), 64bit (`-m64`), and the x32 ABI (`-mx32`).

Also included: a version using repeated subtraction only, which is 9B for unsigned, even for x86-64 mode, and can take one of its inputs in an arbitrary register. However, it can't handle either input being 0 on entry (it detect when `sub` produces a zero, which x - 0 never does).

GNU C inline asm source for the 32bit version (compile with `gcc -m32 -masm=intel`)

```
int gcd(int a, int b) {
    asm (// ".intel_syntax noprefix\n"
        // "jmp  .Lentry%=\n" // Uncomment to handle div-by-zero, by entering the loop in the middle.  Better: `jecxz / jmp` loop structure like the 64b version
        ".p2align 4\n"                  // align to make size-counting easier
         "gcd0:   cdq\n\t"              // sign extend eax into edx:eax.  One byte shorter than xor edx,edx
         "        idiv    ecx\n"
         "        xchg    eax, edx\n"   // there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
         "        xchg    eax, ecx\n"   // eax = divisor(ecx), ecx = remainder(edx), edx = garbage that we will clear later
         ".Lentry%=:\n"
         "        inc     ecx\n"        // saves 1B vs. test/jnz in 32bit mode, none in 64b mode
         "        loop    gcd0\n"
        "gcd0_end:\n"
         : /* outputs */  "+a" (a), "+c"(b)
         : /* inputs */   // given as read-write outputs
         : /* clobbers */ "edx"
        );
    return a;
}

```

Normally I'd write a whole function in asm, but GNU C inline asm seems to be the best way to include a snippet which can have in/outputs in whatever regs we choose. As you can see, GNU C inline asm syntax makes asm ugly and noisy. It's also a really difficult way to *learn* asm.

It would actually compile and work in `.att_syntax noprefix` mode, because all the insns used are either single/no operand or `xchg`. Not really a useful observation.

# Answer
> 15 votes
## Hexagony, 17 bytes

```
?'?>}!@<\=%)>{\.(

```

Unfolded:

```
  ? ' ?
 > } ! @
< \ = % )
 > { \ .
  ( . .

```

Try it online!

Fitting it into side-length 3 was a breeze. Shaving off those two bytes at the end wasn't... I'm also not convinced it's optimal, but I'm sure I think it's close.

### Explanation

Another Euclidean algorithm implementation.

The program uses three memory edges, which I'll call **A**, **B** and **C**, with the memory pointer (MP) starting out as shown:

Here is the control flow diagram:

Control flow starts on the grey path with a short linear bit for input:

```
?    Read first integer into memory edge A.
'    Move MP backwards onto edge B.
?    Read second integer into B.

```

Note that the code now wraps around the edges to the `<` in the left corner. This `<` acts as a branch. If the current edge is zero (i.e. the Euclidean algorithm terminates), the IP is deflected to the left and takes the red path. Otherwise, an iteration of the Euclidean algorithm is computed on the green path.

We'll first consider the green path. Note that `>` and `\` all acts as mirrors which simply deflect the instruction pointer. Also note that control flow wraps around the edges three times, once from the bottom to the top, once from the right corner to the bottom row and finally from the bottom right corner to the left corner to re-check the condition. Also note that `.` are no-ops.

That leaves the following linear code for a single iteration:

```
{    Move MP forward onto edge C.
'}   Move to A and back to C. Taken together this is a no-op.
=    Reverse the direction of the MP so that it now points at A and B.
%    Compute A % B and store it in C.
)(   Increment, decrement. Taken together this is a no-op, but it's
     necessary to ensure that IP wraps to the bottom row instead of
     the top row.

```

Now we're back where we started, except that the three edges have changed their roles cyclically (the original **C** now takes the role of **B** and the original **B** the role of **A**...). In effect, we've relpaced inputs `A` and `B` with `B` and `A % B`, respectively.

Once `A % B` (on edge **C**) is zero, the GCD can be found on edge **B**. Again the `>` just deflects the IP, so on the red path we execute:

```
}    Move MP to edge B.
!    Print its value as an integer.
@    Terminate the program.

```

# Answer
> 11 votes
# T-SQL, 153 ~~169~~ bytes

Someone mentioned worst language for golfing?

```
CREATE FUNCTION G(@ INT,@B INT)RETURNS TABLE RETURN WITH R AS(SELECT 1D,0R UNION ALL SELECT D+1,@%(D+1)+@B%(D+1)FROM R WHERE D<@ and D<@b)SELECT MAX(D)D FROM R WHERE 0=R

```

Creates a table valued function ~~that uses a recursive query to work out the common divisors. Then it returns the maximum~~. Now uses the euclidean algorithm to determine the GCD derived from my answer here.

Example usage

```
SELECT *
FROM (VALUES
        (15,45),
        (45,15),
        (99,7),
        (4,38)
    ) TestSet(A, B)
    CROSS APPLY (SELECT * FROM G(A,B))GCD

A           B           D
----------- ----------- -----------
15          45          15
45          15          15
99          7           1
4           38          2

(4 row(s) affected)

```

# Answer
> 10 votes
# Jelly, 7 bytes

```
ṛß%ðḷṛ?

```

Recursive implementation of the Euclidean algorithm. Try it online!

If built-ins weren't forbidden, `g` (1 byte, built-in GCD) would achieve a better score.

### How it works

```
ṛß%ðḷṛ?  Main link. Arguments: a, b

   ð     Convert the chain to the left into a link; start a new, dyadic chain.
 ß       Recursively call the main link...
ṛ %        with b and a % b as arguments.
     ṛ?  If the right argument (b) is non-zero, execute the link.
    ḷ    Else, yield the left argument (a).

```

# Answer
> 10 votes
## 32-bit little-endian x86 machine code, 14 bytes

Generated using `nasm -f bin`

`d231 f3f7 d889 d389 db85 f475`

```
    gcd0:   xor     edx,edx
            div     ebx
            mov     eax,ebx
            mov     ebx,edx
            test    ebx,ebx
            jnz     gcd0

```

# Answer
> 8 votes
# Python 3, 31

Saved 3 bytes thanks to Sp3000.

```
g=lambda a,b:b and g(b,a%b)or a

```

# Answer
> 7 votes
## Haskell, 19 bytes

```
a#0=a
a#b=b#rem a b

```

Usage example: `45 # 35`-\> `5`.

Euclid, again.

PS: of course there's a built-in `gcd`, too.

# Answer
> 6 votes
# MATL, ~~11~~ 9 bytes

No one seems to have used brute force up to now, so here it is.

```
ts:\a~f0)

```

Input is a column array with the two numbers (using `;` as separator).

**Try it online!** or **verify all test cases**.

### Explanation

```
t     % Take input [a;b] implicitly. Duplicate
s     % Sum. Gives a+b
:     % Array [1,2,...,a+b]
\     % Modulo operation with broadcast. Gives a 2×(a+b) array
a~    % 1×(a+b) array that contains true if the two modulo operations gave 0
f0)   % Index of last true value. Implicitly display

```

# Answer
> 5 votes
# Julia, ~~21~~ 15 bytes

```
a\b=a>0?b%a\a:b

```

Recursive implementation of the Euclidean algorithm. Try it online!

If built-ins weren't forbidden, `gcd` (3 bytes, built-in GCD) would achieve a better score.

### How it works

```
a\b=             Redefine the binary operator \ as follows:
    a>0?     :       If a > 0:
        b%a\a        Resursively apply \ to b%a and a. Return the result.
              b      Else, return b.

```

# Answer
> 5 votes
## TI-Basic, 27 bytes

```
Prompt A,B:While B:B→T:BfPart(A/B→B:T→A:End:A

```

---

**35 byte** recursive solution without `gcd(` or `lcm(` built-ins (requires 2.53 MP operating system or higher, *must be named* `prgmG`):

```
If Ans(2:Then:{Ans(2),remainder(Ans(1),Ans(2:prgmG:Else:Disp Ans(1:End

```

You would pass arguments to the recursive variant as `{A,B}` so for example `{1071, 462}:prgmG` would yield `21`.

# TI-Basic, 10 bytes

```
Prompt A,B:gcd(A,B

```

*Not allowed due to new rule forbidding gcd built-ins*

---

**17 byte** solution without `gcd(` built-in

```
Prompt A,B:abs(AB)/lcm(A,B

```

*Not allowed due to new rule forbidding lcm built-ins*

---

# Answer
> 5 votes
# C, 38 bytes

```
g(x,y){while(x^=y^=x^=y%=x);return y;}

```

# Answer
> 4 votes
## C#, 24 bytes

```
x=(a,b)=>b<1?a:x(b,a%b);

```

# Answer
> 4 votes
# C, 28 bytes

A rather straightforward function implementing Euclid's algorithm. Perhaps one can get shorter using an alternate algorithm.

```
g(a,b){return b?g(b,a%b):a;}

```

If one writes a little main wrapper

```
int main(int argc, char **argv)
{
  printf("gcd(%d, %d) = %d\n", atoi(argv[1]), atoi(argv[2]), g(atoi(argv[1]), atoi(argv[2])));
}

```

then one can test a few values:

```
$ ./gcd 6 21
gcd(6, 21) = 3
$ ./gcd 21 6
gcd(21, 6) = 3
$ ./gcd 6 8
gcd(6, 8) = 2
$ ./gcd 1 1
gcd(1, 1) = 1
$ ./gcd 6 16
gcd(6, 16) = 2
$ ./gcd 27 244
gcd(27, 244) = 1

```

# Answer
> 4 votes
# Cubix, 10 ~~12~~ bytes

```
?v%uII/;O@

```

Try it here

This wraps onto the cube as follows:

```
    ? v
    % u
I I / ; O @ . .
. . . . . . . .
    . .
    . .

```

Uses the Euclidean Method.

`II` Two numbers are grabbed from STDIN and put on the stack
`/` Flow reflected up
`%` Mod the Top of Stack. Remainder left on top of stack
`?` If TOS 0 then carry on, otherwise turn right
`v` If not 0 then redirect down and `u` turn right twice back onto the mod
`/` If 0 go around the cube to the reflector
`;` drop TOS, `O` output TOS and `@` end

# Answer
> 4 votes
## Labyrinth, 18 bytes

```
?}
:
)"%{!
( =
}:{

```

Terminates with an error, but the error message goes to STDERR.

Try it online!

This doesn't feel quite optimal yet, but I'm not seeing a way to compress the loop below 3x3 at this point.

### Explanation

This uses the Euclidean algorithm.

First, there's a linear bit to read input and get into the main loop. The instruction pointer (IP) starts in the top left corner, going east.

```
?    Read first integer from STDIN and push onto main stack.
}    Move the integer over to the auxiliary stack.
     The IP now hits a dead end so it turns around.
?    Read the second integer.
     The IP hits a corner and follows the bend, so it goes south.
:    Duplicate the second integer.
)    Increment.
     The IP is now at a junction. The top of the stack is guaranteed to be
     positive, so the IP turns left, to go east.
"    No-op.
%    Modulo. Since `n % (n+1) == n`, we end up with the second input on the stack.

```

We now enter a sort of while-do loop which computes the Euclidean algorithm. The tops of the stacks contain `a` and `b` (on top of an implicit infinite amount of zeros, but we won't need those). We'll represent the stacks side to side, growing towards each other:

```
    Main     Auxiliary
[ ... 0 a  |  b 0 ... ]

```

The loop terminates once `a` is zero. A loop iteration works as follows:

```
=    Swap a and b.           [ ... 0 b  |  a 0 ... ]
{    Pull a from aux.        [ ... 0 b a  |  0 ... ]
:    Duplicate.              [ ... 0 b a a  |  0 ... ]
}    Move a to aux.          [ ... 0 b a  |  a 0 ... ]
()   Increment, decrement, together a no-op.
%    Modulo.                 [ ... 0 (b%a)  |  a 0 ... ]

```

You can see, we've replaced `a` and `b` with `b%a` and `a` respectively.

Finally, once `b%a` is zero, the IP keeps moving east and executes:

```
{    Pull the non-zero value, i.e. the GCD, over from aux.
!    Print it.
     The IP hits a dead end and turns around.
{    Pull a zero from aux.
%    Attempt modulo. This fails due to division by 0 and the program terminates.

```

# Answer
> 4 votes
# Brachylog, 5 bytes

```
ḋˢ⊇ᵛ×

```

Try it online!

Takes input as a list through the input variable and outputs an integer through the output variable. If you use it as a generator, it actually generates all common divisors, it just does so largest first.

```
         The output is
    ×    the product of the elements of
  ⊇      the maximal sublist
   ᵛ     which is shared by
ḋ        the prime factorization
 ˢ       s of the elements of the input which have them.

```

# Answer
> 3 votes
# Windows Batch, 76 bytes

Recursive function. Call it like `GCD a b` with file name `gcd`.

```
:g
if %2 equ 0 (set f=%1
goto d)
set/a r=%1 %% %2
call :g %2 %r%
:d
echo %f%

```

# Answer
> 3 votes
# MATL, 7 bytes

```
pG1$Zm/

```

**Try it Online!**

**Explanation**

Since we can't explicitly use the builtin GCD function (`Zd` in MATL), I have exploited the fact that the least common multiple of `a` and `b` times the greatest common denominator of `a` and `b` is equal to the product of `a` and `b`.

```
p       % Grab the input implicitly and multiply the two elements
G       % Grab the input again, explicitly this time
1$Zm    % Compute the least-common multiple
/       % Divide the two to get the greatest common denominator

```

# Answer
> 3 votes
## ARM machine code, 12 bytes:

assembly:

```
gcd: cmp r0, r1
     sublt r0, r0, r1
     bne gcd

```

Currently can't compile this, but each instruction in ARM takes 4 bytes. Probably it could be golfed down using THUMB-2 mode.

# Answer
> 3 votes
# \>\<\>, 32 bytes

```
::{::}@(?\=?v{:}-
.!09}}${{/;n/>

```

Accepts two values from the stack and apply the euclidian algorithm to produce their GCD.

You can try it here!

For a much better answer in \>\<\>, check out Sok's !

# Answer
> 3 votes
# Racket (Scheme), 44 bytes

Euclid implementation in Racket (Scheme)

```
(define(g a b)(if(= 0 b)a(g b(modulo a b))))

```

Edit: Didn't see @Numeri 's solution lol. Somehow we got the exact same code independently

# Answer
> 3 votes
# R, ~~39~~ 33 bytes

Surprised not to see an R answer on here yet. A recursive implementation of the Euclidean algorithm. Saved 2 bytes due to Giuseppe.

```
g=pryr::f(`if`(o<-x%%y,g(y,o),y))

```

And here is a vectorized version (**35 bytes**) which works well for problems like Natural pi calculation.

```
g=pryr::f(ifelse(o<-x%%y,g(y,o),y))

```

# Answer
> 3 votes
# Proton, 21 bytes

```
f=(a,b)=>b?f(b,a%b):a

```

Try it online!

Shush you, this is totally not a port of the Python answer.

# Answer
> 3 votes
# ReRegex, 23 bytes

Works identically to the Retina answer.

```
^(_*)\1* \1*$/$1/#input

```

Try it online!

# Answer
> 3 votes
# Add++, 26 bytes

```
D,g,@@#~,%A$p%+
L,MRBCþgbM

```

Try it online!

Generates the range \\$1, 2, 3, ..., \max(a, b)\\$, then filters out elements that don't divide either \\$a\\$ or \\$b\\$, Finally, we return the maximum value of the filtered elements.

# Answer
> 3 votes
# Forth (gforth), <sup>~~37~~</sup> 34 bytes

```
: f dup if tuck mod recurse then ;

```

Try it online!

Same as the code below, but using recursion instead. Turns out that the combination `if then recurse` is shorter than `begin while repeat` by 3 chars, even though the word `recurse` looks quite bulky.

---

### Previous solution, 37 bytes

```
: f begin dup while tuck mod repeat ;

```

Try it online!

Input is two single-cell integers, output is one double-cell integer.

### How it works

A "cell" means a space for one item on the stack. A double-cell integer in Forth takes two cells, where the most significant cell is on the top. For this challenge, the GCD of two single-cell integers always fits in a cell, so the upper cell is always 0.

```
: f ( a b -- d ) \ Define a function f which takes two singles and gives a double
  begin          \ Start a loop
    dup while    \   While b is not zero...
    tuck         \   Copy b under a ( stack: b a b ) and
    mod          \   Calculate a%b  ( stack: b a%b )
                 \   That is, change ( a b ) to ( b a%b )
  repeat ;       \ End loop
                 \ The result is ( gcd 0 ) which is gcd in double-cell

```

# Answer
> 3 votes
## ARMv7 (OakSim), 28 bytes

Hexdump:

```
0x00010000: 01 00 80 E0 00 10 81 E0 01 00 50 E1 01 00 40 C0 ..........P...@.
0x00010010: 00 10 41 B0 FB FF FF 1A 1E FF 2F E1 00 00 00 00 ..A......./.....

```

## Explanation

Callable function, expects the arguments in `r0` and `r1`, output is in `r0`.

Expects address of caller stored in `lr`. This is the standard method of procedure calling as per the ATPCS (ARM Thumb Procedure Call Standard).

```
gcd:
    add r0, r0, r1        /* Make sure r0 is nonzero */
    add r1, r1, r0        /* Make sure r1 is nonzero */
                          /* We're basically doing the inverse afterwards */

    loop:                 /* main loop: */
        cmp r0, r1        /*     Compare r0 and r1 */
        subgt r0, r0, r1  /*     If r0 >  r1: r0 = r0 - r1 */
        sublt r1, r1, r0  /*     If r0 <  r1: r1 = r1 - r0 */
        bne loop          /*     If r0 != r1: jump back to main loop */

    bx lr                 /* return to caller */

```

### Example call

```
b caller       /* jump to the caller */
gcd:
               /* omitted to save space */
caller:
    mov r0, 30 /* first operand  = 30 */
    mov r1, 42 /* second operand = 42 */
    mov lr, pc /* link register  = program counter */

    b gcd      /* branch to function */

```

# Answer
> 2 votes
# Javascript, 21 bytes.

I think I'm doing this right, I'm still super new to Javascript.

```
g=a=>b=>b?g(b)(a%b):a

```

# Answer
> 2 votes
# 05AB1E, 10 bytes

Code:

```
EàF¹N%O>iN

```

Try it online!

---

With built-ins:

```
¿

```

Explanation:

```
¿   # Implicit input, computes the greatest common divisor.
    # Input can be in the form a \n b, which computes gcd(a, b)
    # Input can also be a list in the form [a, b, c, ...], which computes the gcd of
      multiple numbers.

```

Try it online! or Try with multiple numbers.

# Answer
> 2 votes
## Hoon, 20 bytes

```
|=
{@ @}
d:(egcd +<)

```

--

## Hoon #2, 39 bytes

```
|=
{a/@ b/@}
?~
b
a
$(a b, b (mod a b))

```

Oddly, the only implementation in Hoon's stdlib for GCD is the one in use for its RSA crypto, which also returns some other values. I have to wrap it in a function that takes only `d` from the output.

The other implementation is just the default recursive GCD definition.

# Answer
> 2 votes
# GML, 57 bytes

```
a=argument0
b=argument1
while b{t=b;b=a mod b;a=t}return a

```

# Answer
> 2 votes
# Delphi 7, 148

Well, I think I've found the new worst language for golfing.

```
unit a;interface function g(a,b:integer):integer;implementation function g(a,b:integer):integer;begin if b=0then g:=a else g:=g(b,a mod b);end;end.

```

# Answer
> 2 votes
# Python 3.5, 70 82 73 bytes:

```
lambda*a:max([i for i in range(1,max(*a)+1)if not sum(g%i for g in[*a])])

```

The `not` in this case will make sure the sum all the numbers in `*args` modulo `i` are zero.

Also, now this lambda function can take in as many values as you want it to, as long as the amount of values is `>=2`, unlike the `gcd` function of the math module. For instance, it can take in the values `2,4,6,8,10` and return the correct GCD of 2.

# Answer
> 2 votes
# Ruby, 23 bytes

```
g=->a,b{b>0?a:g[b,a%b]}

```

*remember that ruby blocks are called with g\[...\] or g.call(...), instead of g(...)*

*partial credits to voidpigeon*

# Answer
> 2 votes
# Oracle SQL 11.2, ~~104~~ 118 bytes

```
SELECT MAX(:1+:2-LEVEL+1)FROM DUAL WHERE(MOD(:1,:1+:2-LEVEL+1)+MOD(:2,:1+:2-LEVEL+1))*:1*:2=0 CONNECT BY LEVEL<=:1+:2;

```

Fixed for input of 0

# Answer
> 2 votes
# Javascript, 42 bytes

```
n=(x,y)=>{for(k=x;x%k+y%k>0;k--);alert(k)}

```

I could get it down to ~32 with Grond, but whatever

# Answer
> 2 votes
# Scheme, 44 bytes

```
(define(f a b)(if(= b 0)a(f b(modulo a b))))

```

Scheme is the future of code-golf. `:)`

# Answer
> 2 votes
# \>\<\>, 12+3 = 15 bytes

```
:?!\:}%
;n~/

```

Expects the input numbers to be present on the stack, so +3 bytes for the `-v` flag. Try it online!

Another implementation of the Euclidean algorithm.

# Answer
> 2 votes
# Maple, ~~77~~ 75 bytes

```
`if`(min(a,b)=0,max(a,b),max(`intersect`(op(numtheory:-divisors~({a,b})))))

```

Usage:

```
> f:=(a,b)->ifelse(min(a,b)=0,max(a,b),max(`intersect`(op(numtheory:-divisors~({a,b})))));
> f(0,6);
  6
> f(21,12);
  3

```

This uses a Maple deprecated built-in for computing all of the factors for `a` and `b`. The updated built-in is `NumberTheory:-Divisors`.

# Answer
> 2 votes
## Racket 38 bytes

```
  (λ(a b)(if(> b 0)(f b(modulo a b))a))

```

Ungolfed:

```
(define f
  (λ (a b)
    (if (<= b 0)
        a
        (f b (modulo a b))
        )))

```

Testing:

```
(f 0 2)
(f 6 0)
(f 30 42)
(f 15 14)
(f 7 7)
(f 69 25)
(f 21 12)
(f 169 123)
(f 20 142)
(f 101 202)

```

Output:

```
2
6
6
1
7
1
3
1
2
101

```

# Answer
> 2 votes
## Logy, ~~64~~ 23 bytes

```
f[X,Y]->Y<1&X|f[Y,X%Y];

```

Ungolfed:

```
gcd[X, Y] -> Y < 1 & X | gcd[Y, X%Y];

```

EDIT: Removed way too many bytes because there is no need for a full program

# Answer
> 2 votes
# Java 8, ~~44~~ 37 bytes

Here is a straight up, non-recursive (because of the lambda) Euclidean algorithm.

```
(x,y)->{while(y>0)y=x%(x=y);return x}

```

**Update**

* **-7** \[16-10-04\] Simplified `while` condition

# Answer
> 2 votes
# PHP, ~~41~~ 51 bytes

similar to my LCM answer:

```
for($d=1+$a=$argv[1];$argv[2]%--$d||$a%$d;);echo$d;

```

loop `$d` down from `$argv[1]` while `$argv[1]/$d` or `$argv[2]/$d` have a remainder.

# Answer
> 2 votes
# Perl 5, 51 bytes

49bytes of code + 2 flags (`-pa`)

```
$b=pop@F;($_,$b)=(abs$_-$b,$_>$b?$b:$_)while$_-$b

```

Try it online!

# Perl 5, 54 bytes

```
sub g{my($a,$b)=@_;$a-$b?g(abs($a-$b),$a>$b?$b:$a):$a}

```

Try it online!

# Answer
> 2 votes
# Java, 38 bytes

```
f=(int a,b)->{return b==0?a:f(b,a%b);}

```

# Answer
> 2 votes
# tinylisp, 44 bytes

```
(d G(q((a b)(i(l b a)(G b a)(i a(G(s b a)a)b

```

Defines a function `G` that takes two arguments. Try it online!

### Explanation

Since mod is not built into tinylisp, we use a subtraction-based algorithm instead.

(Glossary of tinylisp builtins used: `d` = def, `q` = quote, `i` = if, `l` = less-than, `s` = subtract)

* Define G `(d G` as a function that takes two arguments `(q((a b)`
* If the second argument is smaller `(i(l b a)` then recurse with the arguments swapped `(G b a)`
* Otherwise, if the first argument is nonzero `(i a` then recurse with the new arguments being (larger minus smaller) and (smaller) `(G(s b a)a)`
* Otherwise (the first argument is zero) return the second argument `b`

# Answer
> 2 votes
# Japt, 18 bytes

```
wV Ä o a@!UuX «VuX

```

Brute force, tries every integer.

Try it online!

# Answer
> 2 votes
# Smalltalk, 29 bytes

```
[(a:=b\\(b:=a))>0]whileTrue.b

```

## Explanation

```
a, b                  two integers given as input
b\\(b:=a)             compute (b mod a) and then assign a to b
a:=b\\(b:=a)          assign the remainder just computed to a
[(...)>0]whileTrue    repeat while the reminder a is > 0 (stop otherwise)
b                     return b (the gcd) - dot is a sentence separator

```

# Answer
> 2 votes
# Befunge-93, 22 bytes

```
&&:#v_\.@
p00:<^:\g00%

```

Try it online!

Doesn't beat Jo King's answer, but I already spent the time creating this answer before seeing their solution. C'est la vie. Uses the same Euclidean Algorithm as most answers.

# Answer
> 2 votes
# Japt `-h`, 5 bytes

Input as an array.

```
mâ rf

```

Try it

```
mâ rf     :Implicit input of integer array
m         :Map
 â        :  Divisors
   r      :Reduce by
    f     :  Filtering, keeping only those elements in the first array that also appear in the second
          :Implicit output of last element

```

# Answer
> 2 votes
# APL (NARS2000), 11 chars, 20 bytes

```
{×/(π⍺)∩π⍵}

```

**Examples:**

```
      28{×/(π⍺)∩π⍵}144
4
      69{×/(π⍺)∩π⍵}25
1

```

**Why it works:**

Function `π`, when applied monadically, breaks down argument into prime factors. `(π⍺)∩π⍵` gives intersection of prime factors of left and right argument. `×/` multiplies prime factors in the intersection, giving the largest divisor common to  and `w`. In case  and `w` are co-prime then reducing empty intersection would give `1`.

# Answer
> 2 votes
# Python 3, 58 bytes

```
lambda a,b:max(n for n in range(1,max(a,b)+1)if a%n+b%n<1)

```

Try it online!

# Answer
> 2 votes
# BQN, 11 bytes<sup>SBCS</sup>

```
{(|⊣)⍟}

```

Run online!

3 bytes shorter and a lot less efficient than the version provided on BQNcrate: `{(|⍟(>⟜0)⊣)}`

This is a dyadic function with arguments and .

With left argument and starting with as a right argument, call `(|⊣)` times, updating the right argument with the return value. refers to the full function and `|⊣` does a recursive call with `|` ( mod ) as left and as right argument.

It would be enough to call the inner function just once if is positive, and not at all if is 0, but `⍟(×)` is just too long.

# Answer
> 2 votes
# Rust, 39 bytes

```
|a,b|(1..=a+b).rev().find(|i|a%i+b%i<1)

```

Try it online!

# Answer
> 2 votes
# Javascript, 48 bytes

```
$=((r,a)=>{for(;a;){var e=a;a=r%a,r=e}return r})

```

# Answer
> 2 votes
# Nibbles, 5 bytes (10 nibbles)

```
`;~$@@$_@%

```

## Verbose

```
`;   # Recursive function
  ~ $ @   # Call it with the first two command-line arguments (m,n)
  @   # Recurse if n is truthy
  $   # Base case = m
  _ @ %   # Recursive case = gcd(n, m mod n)

```

# Answer
> 2 votes
# Vyxal, 13 bytes

```
∴ƛ□$%∑¬;¦:Gḟ›

```

Try it Online!

Thanks to *@Fhuvi* for pointing out a bug.

**Explanation:**

```
∴ƛ□$%∑¬;¦:Gḟ›  # Implicit inputs
∴              # Maximum input
 ƛ     ;       # Map over range(1, ^ + 1):
  □$           #  Push input list and swap
    %∑         #  Sum of each input mod the number
      ¬        #  Equals 0?
        ¦      # Cumulative sums of the list
         :G    # Maximum of that list
           ḟ   # Index of that in the cumulative sums
            ›  # Plus one to account for 0-indexing
               # Implicit output

```

# Answer
> 2 votes
# jq, 30 bytes

Takes a list of two numbers

```
until(min<1;[max-min,min])|max

```

Try it online!

# Answer
> 2 votes
# bash, 37

Recursive:

```
g(){ (($2))&&g $2 $[$1%$2]||echo $1;}

```

But for making useful function, I prefer assigning variable in order to avoid forks. So I will prefer this `for` loop:

```
for((i=$1,l=$2;l;k=l,l=i%l,i=k)){ :;}

```

Note: both routines use 37 characters!

**Test cases**

```
for pair in 0\ 2 6\ 0 30\ 42 15\ 14 7\ 7 69\ 25 21\ 12 169\ 123 20\ 142 101\ 202;do
    printf '%4d %4d => %3d\n' $pair $(g $pair)
done
   0    2 =>   2
   6    0 =>   6
  30   42 =>   6
  15   14 =>   1
   7    7 =>   7
  69   25 =>   1
  21   12 =>   3
 169  123 =>   1
  20  142 =>   2
 101  202 => 101

```

### As a dedicated function:

```
gcd() {
    if [[ $1 == -v ]];then local -n i=$2;shift 2;else local i;fi
    local l=$2 k
    for((i=$1;l;k=l,l=i%l,i=k)){ :;}
    [[ ${i@A} != i=* ]] || echo "$i"
}

```

**Test cases**

```
for pair in 0:2 6:0 30:42 15:14 7:7 69:25 21:12 169:123 20:142 101:202;do
    IFS=: read -ra vals <<<$pair
    gcd -v res ${vals[@]}
    printf '    %4d %4d => %3d\n' ${vals[@]} $res
done
   0    2 =>   2
   6    0 =>   6
  30   42 =>   6
  15   14 =>   1
   7    7 =>   7
  69   25 =>   1
  21   12 =>   3
 169  123 =>   1
  20  142 =>   2
 101  202 => 101

```

# Answer
> 2 votes
# Desmos, 44 bytes

```
f(l)=[i0^{mod(l,i).max}fori=[1...l.max]].max

```

Try it on Desmos!

Input is a list of two integers. It won't work if at least one of the inputs is greater than 10000 because of list length limits, so this is possibly non-competing.

# Answer
> 2 votes
# Piet \+ ascii-piet, 42 bytes (2×21=42 codels)

```
qbdijbrlkumldqralckkB   jj   s??venvfff bb

```

Try Piet online!

# Answer
> 2 votes
# Thunno, \\$ 19 \log\_{256}(96) \approx \\$ 15.64 bytes

```
~e1+I$S0=Ez(DMsAh1+

```

Attempt This Online!

Thanks to *@Fhuvi* for pointing out a bug.

#### Explanation

```
~e1+I$S0=Ez(DMsAh1+  # Implicit input
~                    # First non-zero input
 e       E           # Map over the range:
  1+                 #  Increment
    I$               #  Mod the input list
      S0=            #  Sum equals 0
          z(         # Cumulative sums
            DM       # Maximum
              sAh    # Index of this in the list
                 1+  # Incremented
                     # Implicit output

```

Old one which didn't work for 0:

```
eI$S0=Ez(DMsAh  # Implicit input
e     E         # Map over range:
 I$             #  This number mod the input list
   S0=          #  Sum equals 0
       z(       # Cumulative sums
         DM     # Maximum
           sAh  # Index of this in the list
                # Implicit output

```

# Answer
> 2 votes
## C, 23 bytes

```
f(x,y){x=x?f(y%x,x):y;}

```

Essentially Euclid's algorithm in a ternary expression with recursion.

# Answer
> 1 votes
# Mathematica, 27 bytes

```
If[#<1,#2,#0[#2,#~Mod~#2]]&

```

Not much to see here.

# Answer
> 1 votes
## Seriously, 23 bytes

```
,,;'XQ1╟";(%{}"f3δI£ƒkΣ

```

This makes use of the `Q`uine command, which is currently the only sane way to do recursion.

Try it online!

Explanation:

```
,,;'XQ1╟";(%{}"f3δI£ƒkΣ
,,;                      get a and b inputs, duplicate b
   'X                    push "x"
     Q1╟                 push a list containing the program's source code as the singular element
        ";(%{}"f         push the string ";(%{}".format(source_code) (essentially "gcd(b, a % b)")
                3δ       bring the second copy of b to TOS
                  I      if: pop b, recursive call, and "X", and push recursive call if b != 0 else "X"
                   £ƒ    call the string as a function
                     kΣ  sum stack elements (without this, the stack contains the gcd and possibly several 0's)

```

# Answer
> 1 votes
# RETURN, 16 bytes

```
[$[\¤÷%G][\]?]=G

```

`Try it here.`

Recursive operator implementation of Euclid's algorithm. Leaves result on top of stack. Usage:

```
[$[\¤÷%G][\]?]=G21 12G

```

# Explanation

```
[            ]=G  Define operator G
 $                Check if b is truthy
  [     ][ ]?     Conditional
   \¤               If so, create pattern [b a b] on stack
     ÷%             Mod top 2 items
       G            Recurse
          \         Otherwise, swap top 2 items

```

# Answer
> 1 votes
# T-SQL, 147 Bytes

SQL Fiddle

**MS SQL Server 2014 Schema Setup**:

```
CREATE PROC G @ INT,@B INT,@C INT OUT AS BEGIN IF @<@B EXEC G @B,@,@C OUT ELSE IF @B>0 BEGIN SELECT @=@%@B EXEC G @B,@,@C OUT END ELSE SET @C=@ END

```

**Testing**:

Use something like this to generate each set of results:

```
DECLARE @A INT,@B INT,@EXP INT,@RES INT
  SELECT @A=0,@B=2,@EXP=2
  EXEC G @A,@B,@RES OUT
  SELECT @A A,@B B,@EXP EXPECTED,@RES RESULT

```

**Results**:

```
|  A  |  B  | EXPECTED | RESULT |
|-----|-----|----------|--------|
|   0 |   2 |        2 |      2 |
|   6 |   0 |        6 |      6 |
|  30 |  42 |        6 |      6 |
|  15 |  14 |        1 |      1 |
|   7 |   7 |        7 |      7 |
|  69 |  25 |        1 |      1 |
|  21 |  12 |        3 |      3 |
|  20 | 142 |        2 |      2 |
| 101 | 202 |      101 |    101 |

```

# Answer
> 1 votes
# Oracle SQL 11.2, 108 Bytes

```
CREATE PROCEDURE G(A INT,B INT,C OUT INT)AS BEGIN IF A>0 THEN G(LEAST(A,B),ABS(A-B),C);ELSE C:=B;END IF;END;

```

**Testing**:

```
CREATE FUNCTION testHelper(A INT,B INT) RETURN INT
AS
  C INT;
BEGIN
  G(A,B,C);
  RETURN C;
END;
/

WITH tests( A, B, Expected ) AS (
  SELECT   0,  2,  2 FROM DUAL UNION ALL
  SELECT   6,  0,  6 FROM DUAL UNION ALL
  SELECT  30, 42,  6 FROM DUAL UNION ALL
  SELECT  15, 14,  1 FROM DUAL UNION ALL
  SELECT   7,  7,  7 FROM DUAL UNION ALL
  SELECT  69, 25,  1 FROM DUAL UNION ALL
  SELECT  21, 12,  3 FROM DUAL UNION ALL
  SELECT 169,123,  1 FROM DUAL UNION ALL
  SELECT  20,142,  2 FROM DUAL UNION ALL
  SELECT 101,202,101 FROM DUAL
)
SELECT t.*,testHelper(A,B) AS "RESULT"
FROM   tests t;

```

**Output**:

```
         A          B   EXPECTED     RESULT
---------- ---------- ---------- ----------
         0          2          2          2
         6          0          6          6
        30         42          6          6
        15         14          1          1
         7          7          7          7
        69         25          1          1
        21         12          3          3
       169        123          1          1
        20        142          2          2
       101        202        101        101

```

# Answer
> 1 votes
# J, ~~15~~ 14 bytes

```
[`(|$:[)@.(]*)

```

Uses Euclid's algorithm.

## Usage

```
   f =: [`(|$:[)@.(]*)
   30 f 42
6
   42 f 30
6
   169 f 123
1

```

## Explanation

```
[`(|$:[)@.(]*)  Input: a, b
           ]*   Get sign(b)
                If sign(n) = 0
[                 Return a
                Else
   |              Get b mod a
      [           Get a
    $:            Call recursively on (b mod a, a)

```

# Answer
> 1 votes
# Java 7, 42 bytes

```
int c(int a,int b){return b>0?c(b,a%b):a;}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(int a, int b){
    return b > 0
            ? c(b, a%b)
            : a;
  }

  public static void main(String[] a){
    System.out.println(c(0, 2));
    System.out.println(c(6, 0));
    System.out.println(c(30, 42));
    System.out.println(c(15, 14));
    System.out.println(c(7, 7));
    System.out.println(c(69, 25));
    System.out.println(c(21, 12));
    System.out.println(c(169, 123));
    System.out.println(c(20, 142));
    System.out.println(c(101, 202));
  }
}

```

**Output:**

```
2
6
6
1
7
1
3
1
2
101

```

# Answer
> 1 votes
# Befunge-93, 21 bytes

```
&&:v_.@
00:_^#:%g00\p

```

Try it Online

Yet another Euclidean algorithm

# Answer
> 1 votes
# MACHINE LANGUAGE(X86, 32 bit), 19 bytes

```
0000079C  8B442404          mov eax,[esp+0x4]
000007A0  8B4C2408          mov ecx,[esp+0x8]
000007A4  E308              jecxz 0x7ae
000007A6  31D2              xor edx,edx
000007A8  F7F1              div ecx
000007AA  92                xchg eax,edx
000007AB  91                xchg eax,ecx
000007AC  EBF6              jmp short 0x7a4
000007AE  C3                ret
000007AF

```

7AFh-79Ch=13h=19d (see other x86 solution too).Below assembly with the function, but for me gcd(a,b) if a or b is 0 has to return -1 error...

```
; nasmw -fobj  this.asm
; bcc32 -v  file.c this.obj
section _DATA use32 public class=DATA
global _gcda
section _TEXT use32 public class=CODE

_gcda:
      mov     eax,  dword[esp+  4]
      mov     ecx,  dword[esp+  8]
.1:   JECXZ   .z
      xor     edx,  edx
      div     ecx
      xchg    eax,  edx
      xchg    eax,  ecx
      jmp     short  .1
.z:
      ret

```

this is the C function for test, that call the gcda() function:

```
#include <stdio.h>
unsigned v0[]={30,15,7,69,21,169, 20,101,0,6,1,0};
unsigned v1[]={42,14,7,25,12,123,142,202,2,0,2,0};
unsigned gcda(unsigned,unsigned);

main(void)
{int  i;
 for(i=0;v0[i]||v1[i];++i)
    printf("gcd(%u,%u)=%u\n",v0[i],v1[i],gcda(v0[i],v1[i]));
 return 0;
}

```

results:

```
gcd(30,42)=6
gcd(15,14)=1
gcd(7,7)=7
gcd(69,25)=1
gcd(21,12)=3
gcd(169,123)=1
gcd(20,142)=2
gcd(101,202)=101
gcd(0,2)=2
gcd(6,0)=6
gcd(1,2)=1

```

# Answer
> 1 votes
# Japt, 9 bytes

```
V?ßVU%V:U

```

Run it online

**8 bytes** if we can reverse the order of the input:

```
?ßV%UU:V

```

Run it online

# Answer
> 1 votes
# Ink, 29 bytes

```
=i(a,b)
{b:->i(b,a%b)}{a}->->

```

Try it online!

# Answer
> 1 votes
# APL(NARS), 13 chars, 26 bytes

```
{⍵<1:⍺⋄⍵∇⍵∣⍺}

```

test:

```
  g←{⍵<1:⍺⋄⍵∇⍵∣⍺}
  30 g 42
6
  42 g 30
6
  15 g 14
1
  7 g 7
7
  69 g 25
1
  0 g 2
2
  6 g 0
6

```

# Answer
> 1 votes
# AWK, 39 bytes

```
{for(x=$1>$2?$1:$2;$1%x||$2%x;)--x}$0=x

```

Try it online!

Does require that 1 of the inputs be positive. Nothing fancy, but I don't see another `AWK` solution.

# Answer
> 1 votes
## Perl 6, 28 bytes

```
my&f={$^b??f($b,$^a%$b)!!$a}

```

# Answer
> 1 votes
# Forth (gforth), 52 bytes

```
: f begin 2dup max -rot min tuck mod ?dup 0= until ;

```

Try it online!

Uses Euclidean Algorithm \[repeatedly call larger % smaller until result is 0\]

### Code Explanation

```
: f               \ start a new word definition
  begin           \ start and indefinite loop
    2dup          \ duplicate arguments
    max -rot min  \ reorder arguments so the smaller is on top
    tuck          \ make a copy of the smaller argument and move it behind the larger
    mod ?dup 0=   \ get the modulo of the two arguments, then duplicate and check if it is 0
  until           \ end the loop if it is
;                 \ end the word definition

```

# Answer
> 1 votes
# Ral, ~~45~~ 37 bytes

```
,:,+0=0*/-:1+1:+1+:+:1=?0*+0*/:0=1*?.

```

Try it online! (inputs on separate lines)

Commented:

```
,:,                  Input a and b
+0=                  Add a to b
                   Loop:
0*/-                 Subtract b from a
:1+1:+1+:+:1=?       Continue if a >= 0
0*+                  Add b to a
0*/:0=               Swap a and b
1*?                  Continue if b > 0
.                    Print a

```

# Answer
> 1 votes
# Zsh, 29 bytes

```
(($1))&&$0 $[$2%$1] $1||<<<$2

```

Try it online!

# Answer
> 1 votes
# Thunno 2, 10 bytes

```
GıḊp;ṡDGȮ⁺

```

Attempt This Online!

Port of my Vyxal answer.

#### Explanation

```
GıḊp;ṡDGȮ⁺  # Implicit input
Gı  ;       # Map over (the one-range of) the higher number:
  Ḋ         #  Is each input divisible by this number?
   p        #  Are both true?
     ṡ      # Cumulative sums of this list
      DG    # Without popping, push the maximum
        Ȯ⁺  # 1-based index of the maximum
            # Implicit output

```

# Answer
> 1 votes
# Vyxal `G`, 37 bits<sup>v1</sup>, 4.625 bytes

```
vKƒ↔∨

```

Try it Online!

Why use ranges and sums when a more logical approach is shorter :p

Takes input as a list of numbers.

## Explained

```
vKƒ↔∨
vK      # Get the divisors of each number
  ƒ↔    # reduce by set intersection. This will either give a list of shared divisors or an empty list. You only get an empty list if there is a 0 in the input.
     ∨  # logical or with the input, getting the first truthy value. If there's a 0 in the input, this returns the input list
# The G flag gets the biggest of either the shared factors or the input list if there's a 0.

```

# Answer
> 1 votes
# Nekomata, 5 bytes

```
ṀRᶠ¦Ṁ

```

Attempt This Online!

Takes a list of two numbers as input.

```
ṀRᶠ¦Ṁ
Ṁ       Maximum of the input
 R      Range from 1 to that
  ᶠ     Filter by the following function:
   ¦      Check that it divides both numbers in the input
    Ṁ   Maximum of the resulting list

```

---

# Nekomata, 6 bytes

```
ʷ{$ᵉ%Z

```

Attempt This Online!

Using the Euclidean algorithm.

```
ʷ{$ᵉ%Z
ʷ{      Apply the following function repeatedly until it fails:
          Let the stack be a, b
  $       a, b -> b, a
   ᵉ%     b, a -> b, a % b
     Z    Check that b is not zero

```

# Answer
> 0 votes
# Pyth, 2 bytes

```
iE

```

Try it here!

Input as integer on two separate lines. Just uses a builtin.

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