[Question]
  [
Your task is to compute the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) 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](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") 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]
# [Retina](https://github.com/mbuettner/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.](http://retina.tryitonline.net/#code=XiguKylcMSogXDErJAokMQ&input=MTExMTExMTEgMTExMTExMTExMTEx) - 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.](http://retina.tryitonline.net/#code=XGQrCiQqCl4oLispXDEqIFwxKyQKJDEKMSsKJC4m&input=NCA4)
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]
## 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](https://stackoverflow.com/questions/35742570/why-is-the-loop-instruction-slow-couldnt-intel-have-implemented-it-efficiently)), 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](http://gcc.godbolt.org/#compilers:!((compiler:g510,options:%27-xc+-Wall+-Wextra+-std%3Dgnu11+-fverbose-asm+-O3+-m32+-masm%3Dintel+-mtune%3Dintel%27,sourcez:PTAEEMBtNBLA7Azk0BXRBTAJhATh0DWAFwAsNdREEBzSDAWgHsAHC8eHJygDwGNSNADRUmoMrEQQ%2BxVFEgBPUAHduAaynKSpUADpwxYgH1EC%2BMXA9Q8VvgBmsHgCgQoAEKpioPkwC2LWHoVbVAGX3BEXwBeBGIMGAAjDD5wdAIyAiYMygA3CmomeFAACgQ%2BSFQsbFA7blB7Cgx4PgwAShUmVEgcBPxwNV0XMDDZeAwY83jQGib2OKlIQppQADkAeQAFKQREOPAuO1Bw%2BCVqeDpGBIU41c3EEVrKDNAEhHBcJU7iFk8nIdAAMJ%2BAL0KQcHCqXAabzcfAyRQ1OphADMACYSmjXl4fFVWiI6gA2AAsWJhVQAXKFfDw0aAkb5iYMnLsDLA%2BHBzNM%2BFhSpzwCJYi92gBvJygcUQSIlVwAIl0sXiJjMFisNhY9kcAB14DKxRLQDKAFb%2BcW6AAyTWIHwApFFtTLQK4AKrNPy%2BS3iMSkcFBLCwHIMK4MABeFCYIiuhEmu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xTWkfS%2Bv8Q8r2obqgQTe3JxN4dnQClTKrWUifUxKEGGStrdM5UdfJoBpP7VwPy9or0XhWUTsnLw3o8hriSMmUsMcxD0DNnwOZ0HlDejiH2f1jtzCIEWmU%2BAT0jM2ZqejKQrrGkkFo0DUpaSOkQ2eotSVrChm1oxk4bGuMyi0wIIzYgfomCsw5tTcolRStMztgkKrYzit1YZhETAslmuCkcbyOjuALwiAEO8Fa7waA5HvU%2Bm6urxQdYoMQY6A2%2BBs1RNl8Ugp%2BGWQMEwWAi3xv3pKlNiMLltu7bGxN1EU2y0Sjzt7YojLijWiwCIJ77RLJPbpJQbOn2s6oHtDfCMIhRrHSENdIHs9lkcAsCDsHXIsAmBVTD9oAy8YExuaAYmpNyZEkpvqHOoSXINkAuLPbE3DsiBWE6M0ZoRCXkcpAHslkiedGgKT%2B9l2KdU5p6AOn13xS3eIHYe7wPrTQFQC9sXb2s5i9AFz/7cURAM/B1geexRQlCAZ8jpG4zOCTKlblool5RlAAAA%3D)),filterAsm:(binary:!t,commentOnly:!t,directives:!t,intel:!t,labels:!t),version:3)**, for the 32 and 64b versions. Tested and working for 32bit (`-m32`), 64bit (`-m64`), and the [x32 ABI (`-mx32`)](https://en.wikipedia.org/wiki/X32_ABI).
Also included: a version using [repeated subtraction only](http://www.naturalnumbers.org/EuclidSubtract.html), 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](https://stackoverflow.com/questions/34520013/using-base-pointer-register-in-c-inline-asm/34522750#34522750).
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]
## [Hexagony](https://github.com/mbuettner/hexagony), 17 bytes
```
?'?>}!@<\=%)>{\.(
```
Unfolded:
```
  ? ' ?
 > } ! @
< \ = % )
 > { \ .
  ( . .
```
[Try it online!](http://hexagony.tryitonline.net/#code=Pyc_Pn0hQDxcPSUpPntcLig&input=MzAgNDI)
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:
[![enter image description here](https://i.stack.imgur.com/FqWtR.png)](https://i.stack.imgur.com/FqWtR.png)
Here is the control flow diagram:
[![enter image description here](https://i.stack.imgur.com/xI54F.png)](https://i.stack.imgur.com/xI54F.png)
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]
# 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](https://codegolf.stackexchange.com/a/58831/31347).
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]
## 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]
# Jelly, 7 bytes
```
ṛß%ðḷṛ?
```
Recursive implementation of the Euclidean algorithm. [Try it online!](http://jelly.tryitonline.net/#code=4bmbw58lw7DhuLfhuZs_&input=&args=MTI+MTU)
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]
# Python 3, 31
Saved 3 bytes thanks to Sp3000.
```
g=lambda a,b:b and g(b,a%b)or a
```
[Answer]
## 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]
# [MATL](https://esolangs.org/wiki/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!**](https://tio.run/##y00syfn/v6TYKiaxLs1A8///aGMDaxOjWAA) or [**verify all test cases**](https://tio.run/##HYoxEoAgDAR7f2KXBJDRa32CHTAjjZVWUvv1GGhu5/buqe3WU9u75fpdNOt@aCJImdICsnQE3xsHsDdGxL6tkGAUBo/VBIvrhuw3FDGEpPw).
### 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]
# Julia, ~~21~~ 15 bytes
```
a\b=a>0?b%a\a:b
```
Recursive implementation of the Euclidean algorithm. [Try it online!](http://julia.tryitonline.net/#code=YVxiPWE-MD9iJWFcYTpiCgpmb3IgKGEsYikgaW4gKCgwLDIpLCAoNiwwKSwgKDMwLDQyKSwgKDE1LDE0KSwgKDcsNyksICg2OSwyNSksICgyMSwxMiksICgxNjksMTIzKSwgKDIwLDE0MiksICgxMDEsIDIwMikpCiAgICBAcHJpbnRmKCIlM2QgJTNkID0-ICUzZFxuIixhLGIsYVxiKQplbmQ&input=)
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]
# C, 38 bytes
```
g(x,y){while(x^=y^=x^=y%=x);return y;}
```
[Answer]
## 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]
# 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]
## [Labyrinth](https://github.com/mbuettner/labyrinth/), 18 bytes
```
?}
:
)"%{!
( =
}:{
```
Terminates with an error, but the error message goes to STDERR.
[Try it online!](http://labyrinth.tryitonline.net/#code=P30KOgopIiV7IQooID0KfTp7&input=MzAgNDI)
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]
# [Cubix](https://github.com/ETHproductions/cubix), 10 ~~12~~ bytes
```
?v%uII/;O@
```
[Try it here](https://ethproductions.github.io/cubix)
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]
## C#, 24 bytes
```
x=(a,b)=>b<1?a:x(b,a%b);
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ḋˢ⊇ᵛ×
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@GO7tOLHnW1P9w6@/D0//@jFaINdIxidaLNdAyApLGBjgmIZ2iqY2gCpM11zEFyljpGpkDayFDHECwLFDA0MgaJGADVgYUMDHWMDIxiFWIB "Brachylog – 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]
# 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]
# MATL, 7 bytes
```
pG1$Zm/
```
[**Try it Online!**](http://matl.tryitonline.net/#code=cEcxJFptLw&input=WzE1LDNd)
**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]
## 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]
# 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]
# [><>](https://esolangs.org/wiki/Fish), 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](https://fishlanguage.com/playground)!
For a much better answer in ><>, check out [Sok's](https://codegolf.stackexchange.com/a/81126/41881) !
[Answer]
# 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](https://codegolf.stackexchange.com/a/95256/59052).
```
g=pryr::f(ifelse(o<-x%%y,g(y,o),y))
```
[Answer]
# [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 23 bytes
Works identically to the Retina answer.
```
^(_*)\1* \1*$/$1/#input
```
[Try it online!](https://tio.run/##K0otSk1Prfj/P04jXkszxlBLAYhV9FUM9ZUz8wpKS/7/j4cChXgkAAA "ReRegex – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 21 bytes
```
f=(a,b)=>b?f(b,a%b):a
```
[Try it online!](https://tio.run/##RY7BCsMgEETvfsVeCm7Zg5qkIQHbDyk9KFTwEoPxVvrt1jRo9jTDmxl2jSGFJWenuSGL@m4fjlsyF4uzyem9pQ00PBmU44JAIR36RiCq7groG5EDgeyrGwnG1pnKwFCdkiV3tnYoVdeo2FdOLEpaCYXsxZgLETzMcLz3@SfW6JfEHb96RPbNPw "Proton – Try It Online")
Shush you, this is totally not a port of the Python answer.
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 26 bytes
```
D,g,@@#~,%A$p%+
L,MRBCþgbM
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ13HwUG5TkfVUaVAVZvLR8c3yMn58L70JN//KjmJuUkpiQqGdvZ29lz@//8bG/w3MQIA "Add++ –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]
## [ARMv7](https://www.arm.com/) ([OakSim](https://github.com/Wunkolo/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]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), ~~37~~ 34 bytes
```
: f dup if tuck mod recurse then ;
```
[Try it online!](https://tio.run/##TY5BDoIwEEX3c4of95JOQYgaPYkbAkWISMlQ9Pg4khTtpnnzX@e38RLa/b35XstyQoN6HtE1CHP1wNPXEFfNMjmE1g04qxLcFAjwLydIVj3BDaN0Q0B4e5Ryn9AN8FI7UTHZ4XLFDuuJYini3xpqX4JKYliVfa@zcqjjwtbpD6a5D3QmMrBrvZqWcpgIOaUGmf0hH8BZRKYCRYSC8iPs4ZdZBm8vU2KN2aZ/udFVf7VsGNZsA8XlAw "Forth (gforth) – 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!](https://tio.run/##TY3NboNADITvfopR7kXrJQG1UfskuWzZ5UelLDJLeHzqIm0SX6zxfJ5po6T@rWv/175/oMV36IYJfp2x9cMYkNbmB7/RQ8IcXMJVqRSWREC8B0FxsAVumGWYEtIW4aRboClRfBAFixM@v3DCMRl0InFTs4Uv0Eg2GzeOenOTz4F90O5lHRNdiQzsUa@kpQomi4pKg7N9Sr6Az1ky1aizqKl6h708Pcvgx2dJrDbb8sU3GvVSy4ZhzeOgcv8D "Forth (gforth) – 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]
# GML, 57 bytes
```
a=argument0
b=argument1
while b{t=b;b=a mod b;a=t}return a
```
[Answer]
# 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.
```
]