g | x | w | all
Bytes Lang Time Link
080SAKO250323T162801ZAcrimori
005Nekomata230609T082159Zalephalp
023C230610T122430ZZoey
4625Vyxal G230608T223942Zlyxal
010Thunno 2230608T191102ZThe Thon
029Zsh230309T190656Zroblogic
nan230309T170010ZThe Thon
013Vyxal230108T143123ZThe Thon
nanPiet + asciipiet230308T052515ZParcly T
044Desmos230308T041916ZYouserna
037bash230108T162733ZF. Hauri
030jq230108T151044Zpmf
027TIBasic160407T183014ZTimtech
023Logy161003T115710ZTuxCraft
510Nibbles220121T001910Zxigoi
048Javascript211218T142231Zsheepsbl
039Rust211218T133822ZEzhik
011BQN211217T190740Zovs
058Python 3211217T184148ZLarry Ba
034Forth gforth191013T235312ZBubbler
028ARMv7 OakSim200919T104544Zuser9649
020APL NARS2000200919T150318Zjimfan
037Ral200919T121421ZEndenite
005Japt h200919T115916ZShaggy
052Forth gforth191010T200542Zreffu
026Add++191008T203358Zcaird co
022Befunge93190611T160707ZJPeroute
005Brachylog190605T014627ZUnrelate
028Perl 6190319T192425Zbb94
039AWK190319T174703ZRobert B
029Smalltalk190319T121752ZLeandro
026APLNARS190319T091347Zuser5898
019MACHINE LANGUAGEX86190318T204954Zuser5898
029Ink190318T212029ZSara J
009Japt190318T211518ZOliver
009MATL160408T191311ZLuis Men
018Japt190318T022919ZQuintec
038C171228T234114ZHow Chen
021Javascript160407T182010ZMorgan T
021Befunge93171219T071444ZJo King
021Proton170818T201248Ztotallyh
044tinylisp171218T062430ZDLosc
023ReRegex171218T015018ZATaco
038Java171217T235516ZJustin
051Perl 5170907T052305ZXcali
033R161004T140333Zrturnbul
027Mathematica160407T183729ZLegionMa
038Racket161001T170559Zrnso
051PHP161004T142950ZTitus
031Python 3160407T180956ZMorgan T
037Java 8161004T134224ZNonlinea
032><>160408T124905ZAaron
024C#160407T181417ZMorgan T
042Javascript160408T200438ZBald Ban
042Java 7160907T095259ZKevin Cr
010Cubix160408T192308ZMickyT
075Maple160803T012732ZDSkoog
014J160602T202000Zmiles
044Racket Scheme160602T142101ZSimon Ze
nan><>160602T094259ZSok
015Julia160407T181732ZDennis
108Oracle SQL 11.2160410T234601ZMT0
147TSQL160410T231350ZMT0
118Oracle SQL 11.2160408T152947ZJeto
023Seriously160407T191030Zuser4594
017Hexagony160410T094501ZMartin E
018Labyrinth160410T092527ZMartin E
016RETURN160410T043423ZMama Fun
044Scheme160410T040106ZNumeri
089i386 x8632 machine code160408T020012ZPeter Co
01005AB1E160407T182638ZAdnan
007Jelly160407T180840ZDennis
012ARM machine code160408T113436Zstyrofoa
016Retina160407T233652ZDigital
023Ruby160407T211213ZLuis Mas
073Python 3.5160407T192949ZR. Kap
007MATL160408T001426ZSuever
153TSQL160407T202401ZMickyT
020Hoon160407T183558ZRenderSe
019Haskell160407T210824Znimi
028C160407T194544ZCL-
076Windows Batch160407T190159ZTimtech
148Delphi 7160407T185209ZMorgan T
01432bit littleendian x86 machine code160407T184759ZMike Shl
057GML160407T183637ZTimtech
002Pyth160407T180546ZDenker

SAKO, 80 bytes

PODPROGRAM:G(A,B)
CALKOWITE:A,B
GDYB>0:1,INACZEJ2
1)A=G(B,MOD(A,B))
2)G()=A
WROC

This is yet another Euclidean algorithm solution using a recursive function.
This time, however... it's in SAKO! :)

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

C, 23 bytes

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

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

Vyxal G, 37 bitsv1, 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.

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

Zsh, 29 bytes

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

Try it online!

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

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

Piet + ascii-piet, 42 bytes (2×21=42 codels)

qbdijbrlkumldqralckkB   jj   s??venvfff bb

Try Piet online!

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.

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

jq, 30 bytes

Takes a list of two numbers

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

Try it online!

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


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

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)

Javascript, 48 bytes

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

Rust, 39 bytes

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

Try it online!

BQN, 11 bytesSBCS

{𝕨(|𝕊⊣)⍟𝕨𝕩}

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.

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!

Forth (gforth), 37 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

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 */

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.

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

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

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
    

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.

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.

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.

Perl 6, 28 bytes

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

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.

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

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

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

Ink, 29 bytes

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

Try it online!

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

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

Japt, 18 bytes

wV Ä o a@!UuX «VuX

Brute force, tries every integer.

Try it online!

C, 38 bytes

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

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

Befunge-93, 21 bytes

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

Try it Online

Yet another Euclidean algorithm

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.

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)

ReRegex, 23 bytes

Works identically to the Retina answer.

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

Try it online!

Java, 38 bytes

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

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!

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

Mathematica, 27 bytes

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

Not much to see here.

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

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.

Python 3, 31

Saved 3 bytes thanks to Sp3000.

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

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

><>, 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 !

C#, 24 bytes

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

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

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

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

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.

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)

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

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

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.

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 

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 |

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

Seriously, 23 bytes

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

This makes use of the Quine 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)

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:

enter image description here

Here is the control flow diagram:

enter image description here

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.

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.

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

Scheme, 44 bytes

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

Scheme is the future of code-golf. :)

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.

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.

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

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.

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.

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

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.

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

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)

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.

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.

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

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%

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.

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

GML, 57 bytes

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

Pyth, 2 bytes

iE

Try it here!

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