Greatest Common Divisor

40

5

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

Mike Shlanta

Posted 2016-04-07T05:29:54.567

Reputation: 635

1If we're allowing asm to have inputs in whatever registers are convenient, and the result in whatever reg is convenient, we should definitely be allowing functions, or even code fragments (i.e. just a function body). Making my answer a complete function would add about 4B with a register calling convention like MS's 32bit vectorcall (one xchg eax, one mov, and a ret), or more with a stack calling convention. – Peter Cordes – 2016-04-08T23:05:59.480

@PeterCordes Sorry, I should have been more specific. You can totally just write the bear necessary code but if you would be so kind as to include a way to run said code it would be nice. – Mike Shlanta – 2016-04-09T18:59:08.530

So count just the gcd code, but provide the surrounding code so people can verify / experiment / improve? BTW, your test-cases with zero as one of the two inputs break our x86 machine code answers. div by zero raises a hardware exception. On Linux, your process gets a SIGFPE. – Peter Cordes – 2016-04-09T19:30:59.903

@Martin Doesn't your edit make it impossible to implement this in languages where the default integer type is immutable and only limited by the available memory? – CodesInChaos – 2016-04-10T12:24:16.317

3@CodesInChaos Memory and time limitations are usually ignored as long as the algorithm itself can in principle handle all inputs. The rule is just meant to avoid people hardcoding arbitrary limits for loops that artificially limits the algorithm to a smaller range of inputs. I don't quite see how immutability comes into this? – Martin Ender – 2016-04-10T14:10:35.350

1gcd(0,n) is error not n – RosLuP – 2019-03-18T12:33:49.453

Answers

37

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.

Digital Trauma

Posted 2016-04-07T05:29:54.567

Reputation: 64 644

2I would like to vote for this more – MickyT – 2016-04-08T01:51:05.107

Should be fine with the number range now. I've changed the spec (with the OPs permission) to require only the language's natural number range (or [0,255] if that's more). You'll have to support zeroes though, although I think changing your +s to *s should do. And you can significantly shorten the last stage of the long code by reducing it to 1. – Martin Ender – 2016-04-10T09:14:01.743

2

For future reference, I just found an alternative 16-byte solution that works for an arbitrary number of inputs (including one) so it might be more useful in other contexts: http://retina.tryitonline.net/#code=XigxKykoID9cMSkqJAokMQ&input=MTExMTExMTEgMTExMTExMTExMTEx

– Martin Ender – 2016-09-23T11:15:20.290

1Just noticed that neither your solutions nor the one in my comment above needs the ^, because it's impossible for the match to fail from the starting position. – Martin Ender – 2017-12-18T11:01:51.767

28

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.

Peter Cordes

Posted 2016-04-07T05:29:54.567

Reputation: 2 810

2@MikeShlanta: Thanks. If you like optimizing asm, have a look at some of my answers over on stackoverflow. :) – Peter Cordes – 2016-04-08T03:19:32.423

2@MikeShlanta: I found a use for jrcxz after all in the uint64_t version :). Also, didn't notice that you'd specified unsigned, so I included byte counts for that, too. – Peter Cordes – 2016-04-08T22:54:04.497

Why couldn't you use jecxz in the 32-bit version to the same effect? – Cody Gray – 2016-08-13T13:32:14.410

1@CodyGray: inc/loop is 3 bytes in the 32-bit version, but 4B in the 64-bit version. That means that in the 64-bit version only, it doesn't cost extra bytes to use jrcxz and jmp instead of inc / loop. – Peter Cordes – 2016-08-13T14:43:08.630

Can't you point to the middle as entry? – l4m2 – 2017-12-18T20:31:02.767

@l4m2: Yes, you can. But not with inline asm. Good point, I should update this answer to leave out the +1B for handling 0 on entry. Oh, but this is only a snippet, not a function, and in asm it's not free if the surrounding code can't just fall into / out of it. If I want it to be a function, I need to include a ret. (This was one of my first answers. I normally post functions now, but this question was originally written to allow a snippet, not a function.)

– Peter Cordes – 2017-12-18T20:37:28.700

The current question seem doesn't say to allow snippet – l4m2 – 2017-12-18T20:47:49.780

@l4m2: yeah, I know, but I'm just going to leave it alone. I'm going to let myself get away with it on a technicality, because it's just one byte either way, and I don't want to take the time to re-edit the answer. It wasn't the OP's edit that changed it; it was originally written as an ASM-encouraging question, but a mod changed it to be a normal code-golf question. I answered the original question, so I think it's fine to leave it. – Peter Cordes – 2017-12-18T20:52:55.880

14

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.

Martin Ender

Posted 2016-04-07T05:29:54.567

Reputation: 184 808

9

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

Dennis

Posted 2016-04-07T05:29:54.567

Reputation: 196 637

That almost feels like cheating haha, I may have to specify that answers can't use butlins... – Mike Shlanta – 2016-04-07T18:14:57.657

13If you decide to do so, you should do it quickly. It would currently invalidate three of the answers. – Dennis – 2016-04-07T18:16:20.540

Notice he specified length is in bytes -- those characters are mostly > 1 byte in UTF8. – cortices – 2016-04-08T03:45:59.480

8

@cortices Yes, all code golf contests are scored in bytes by default. However, Jelly doesn't use UTF-8, but a custom code page that encodes each of the 256 characters it understands as a single byte.

– Dennis – 2016-04-08T04:31:09.637

@Dennis ah, clever. – cortices – 2016-04-09T01:06:41.963

9

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

Mike Shlanta

Posted 2016-04-07T05:29:54.567

Reputation: 635

4I got this down to 8 bytes by using cdq and signed idiv, and one-byte xchg eax, r32 instead of mov. For 32bit code: inc/loop instead of test/jnz (I couldn't see a way to use jecxz, and there's no jecxnz). I posted my final version as a new answer since I think the changes are big enough to justify it. – Peter Cordes – 2016-04-08T02:05:38.147

9

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)

MickyT

Posted 2016-04-07T05:29:54.567

Reputation: 11 735

1Jesus that is verbose. – Cyoce – 2016-04-09T07:46:35.527

7

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.

nimi

Posted 2016-04-07T05:29:54.567

Reputation: 34 639

you should explain the trick that reverses the input order to avoid the conditional check – proud haskeller – 2016-04-09T01:13:48.800

@proudhaskeller: what trick? Everybody uses this algorithm, i.e. stopping on 0 or going on with the modulus. – nimi – 2016-04-09T23:59:21.533

Nevrmind, everybody is using the trick – proud haskeller – 2016-04-10T07:10:41.157

This, less golfed, is almost exactly what's in Prelude – Michael Klein – 2016-06-01T05:21:55.660

6

Python 3, 31

Saved 3 bytes thanks to Sp3000.

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

Morgan Thrapp

Posted 2016-04-07T05:29:54.567

Reputation: 3 574

3In Python 3.5+: from math import*;gcd – Sp3000 – 2016-04-07T18:11:29.820

@Sp3000 Nice, I didn't know they had moved it to math. – Morgan Thrapp – 2016-04-07T18:12:32.497

1While you're at it: g=lambda a,b:b and g(b,a%b)or a – Sp3000 – 2016-04-07T18:15:00.560

@Sp3000 Thanks! I just finished a recursive solution, but that's even better than what I had. – Morgan Thrapp – 2016-04-07T18:16:15.200

Built-ins for GCD and LCM are disallowed, so the 2nd solution wouldn't be valid. – mbomb007 – 2016-10-04T14:38:59.153

@mbomb007 I'll remove it. That rule didn't exist when I added that one. – Morgan Thrapp – 2016-10-04T14:43:52.257

6

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

Luis Mendo

Posted 2016-04-07T05:29:54.567

Reputation: 87 464

5

C, 38 bytes

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

How Chen

Posted 2016-04-07T05:29:54.567

Reputation: 151

1You need to include the definition of the function in your bytecount. – Rɪᴋᴇʀ – 2017-12-29T00:24:37.657

1@Riker sorry for that, I add the definition and update the count – How Chen – 2017-12-29T00:32:23.170

You can save two bytes by naming the function just g instead of gcd. – Steadybox – 2017-12-29T00:37:03.607

@Steadybox ok, yes, first time join this community:) – How Chen – 2017-12-29T00:38:04.887

Welcome to the site! – Steadybox – 2017-12-29T00:38:28.567

1Welcome to PPCG! – Rɪᴋᴇʀ – 2017-12-29T00:38:31.227

4

C#, 24 bytes

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

Morgan Thrapp

Posted 2016-04-07T05:29:54.567

Reputation: 3 574

4

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.

Dennis

Posted 2016-04-07T05:29:54.567

Reputation: 196 637

4

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

CL-

Posted 2016-04-07T05:29:54.567

Reputation: 751

4

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

MickyT

Posted 2016-04-07T05:29:54.567

Reputation: 11 735

I just wrote up a 12-byte Cubix answer, then started scrolling through the answers to see if I needed to handle both 0,x and x,0... then I came across this. Nice one! – ETHproductions – 2016-10-04T15:05:21.803

4

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.

Martin Ender

Posted 2016-04-07T05:29:54.567

Reputation: 184 808

3

ReRegex, 23 bytes

Works identically to the Retina answer.

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

Try it online!

ATaco

Posted 2016-04-07T05:29:54.567

Reputation: 7 898

3

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%

Timtech

Posted 2016-04-07T05:29:54.567

Reputation: 12 038

3

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

Suever

Posted 2016-04-07T05:29:54.567

Reputation: 10 257

You can save one byte with two separate inputs: *1MZm/ – Luis Mendo – 2016-04-08T18:59:16.417

3

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

Aaron

Posted 2016-04-07T05:29:54.567

Reputation: 3 689

1I found a new language today :) – nsane – 2016-10-01T20:19:50.077

3

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

kronicmage

Posted 2016-04-07T05:29:54.567

Reputation: 111

Does this work in both? – NoOneIsHere – 2016-06-02T15:42:19.983

@NoOneIsHere yeah it works in both – kronicmage – 2016-06-03T12:53:39.710

2

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.

totallyhuman

Posted 2016-04-07T05:29:54.567

Reputation: 15 378

1Conditional operator is shorter: f=(x,y)=>y? f(y,x%y):x (yes the space is necessary due to an interpreter bug) – Business Cat – 2017-08-18T20:14:05.460

...Right, I need to start thinking Proton, not Python. Thanks! – totallyhuman – 2017-08-18T20:16:29.007

2

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!

Xcali

Posted 2016-04-07T05:29:54.567

Reputation: 7 671

2

Java, 38 bytes

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

Justin

Posted 2016-04-07T05:29:54.567

Reputation: 443

2Welcome to PPCG! – Rɪᴋᴇʀ – 2017-12-18T00:58:33.797

@Ricker thanks :) (I'm assuming that stands for programming puzzles code golf) – Justin – 2017-12-18T01:45:11.550

2

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

DLosc

Posted 2016-04-07T05:29:54.567

Reputation: 21 213

2

Japt, 18 bytes

wV Ä o a@!UuX «VuX

Brute force, tries every integer.

Try it online!

Quintec

Posted 2016-04-07T05:29:54.567

Reputation: 2 801

2

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.

Unrelated String

Posted 2016-04-07T05:29:54.567

Reputation: 5 300

2

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.

caird coinheringaahing

Posted 2016-04-07T05:29:54.567

Reputation: 13 702

2

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

Morgan Thrapp

Posted 2016-04-07T05:29:54.567

Reputation: 3 574

That won't work. You define g as curried monads, yet use is as a dyadic function. – Dennis – 2016-04-07T18:21:45.977

@Dennis I think I just fixed it? Like I said, super new to JS. – Morgan Thrapp – 2016-04-07T18:22:36.410

2Yes, that works. For the record, g=(a,b)=>b?a:g(b,a%b) is equally short. – Dennis – 2016-04-07T18:23:41.440

@Dennis Ahhhh, that's what I was missing. I forgot the parens around the arguments and it was throwing syntax errors. – Morgan Thrapp – 2016-04-07T18:24:19.787

2Did you intend to put the ternary values the other way around? g=a=>b=>b?g(b)(a%b):a – user81655 – 2016-04-08T03:39:01.470

Doesn't work when a is less than b – ericw31415 – 2017-11-24T02:38:15.297

@ericw31415 Yes it does: if a<b, then a%b == a, and so the recursive case essentially does g(b)(a), swapping the arguments so that a is now larger. A particularly elegant feature of this algorithm! – DLosc – 2017-12-18T06:16:25.377

@DLosc Wait, this solution doesn't even work for all of the test cases... – ericw31415 – 2017-12-20T23:55:12.193

@ericw31415 See user81655's comment. When the ternary is switched around, it should work. – DLosc – 2017-12-21T00:14:39.133

@DLosc True. I was originally looking for a GCD function to save work in this answer but this wouldn't work so I came up with my own solution. Seems like I ended up with the same thing as user81665.

– ericw31415 – 2017-12-21T02:06:16.123

2

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.

Adnan

Posted 2016-04-07T05:29:54.567

Reputation: 41 965

2

TI-Basic, 10 bytes

Prompt A,B:gcd(A,B

Non-competing due to new rule forbidding gcd built-ins


17 byte solution without gcd( built-in

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

Non-competing due to new rule forbidding lcm built-ins


27 byte solution without gcd( or lcm( built-in:

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.

Timtech

Posted 2016-04-07T05:29:54.567

Reputation: 12 038

Color me impressed. – Mike Shlanta – 2016-04-07T18:57:41.783

You should probably mention that the last one needs to be saved as prgmG. – a spaghetto – 2016-04-07T19:48:15.073

2

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.

RenderSettings

Posted 2016-04-07T05:29:54.567

Reputation: 620

2

GML, 57 bytes

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

Timtech

Posted 2016-04-07T05:29:54.567

Reputation: 12 038

2

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.

Morgan Thrapp

Posted 2016-04-07T05:29:54.567

Reputation: 3 574

Oh I don't know, parenthetic is pretty poor for golfing

– MickyT – 2016-04-07T20:00:41.767

2

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.

R. Kap

Posted 2016-04-07T05:29:54.567

Reputation: 4 730

1You're under arrest for multichar variable names. (Or function arguments, but whatever) – CalculatorFeline – 2016-04-08T02:32:46.707

2

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

Luis Masuelli

Posted 2016-04-07T05:29:54.567

Reputation: 141

2Instead of g.call(a,b) you can use g[a,b]. Instead of proc{|a,b|, you can use ->a,b{. – afuous – 2016-04-07T23:33:09.063

1You can also save one byte by using b>0 instead of b<=0 and switching the order of the other operands. – afuous – 2016-04-07T23:35:27.187

2

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.

styrofoam fly

Posted 2016-04-07T05:29:54.567

Reputation: 151

Nice job man anyone who does this in machine code gets serious props from me. – Mike Shlanta – 2016-04-08T20:15:24.717

This appears to be an attempt at Euclid's algo using only subtraction, but I don't think it works. If r0 > r1 then sublt will do nothing (lt predicate is false) and bne will be an infinite loop. I think you need a swap if not lt, so the same loop can do b-=a or a-=b as needed. Or a negate if the sub produced carry (aka borrow).

– Peter Cordes – 2016-04-09T18:55:45.123

This ARM instruction set guide actually uses a subtraction GCD algorithm as an example for predication. (pg 25). They use cmp r0, r1 / subgt r0, r0, r1 / sublt r1, r1, r0 / bne gcd. That's 16B in ARM instructions, maybe 12 in thumb2 instructions?

– Peter Cordes – 2016-04-09T19:21:20.717

1On x86, I managed 9 bytes with: sub ecx, eax / jae .no_swap / add ecx,eax / xchg ecx,eax / jne. So instead of a cmp, I just sub, then undo and swap if the sub should have gone the other way. I tested this, and it works. (add won't make jne exit at the wrong time, because it can't produce a zero unless one of the inputs was zero to start with, and we don't support that. Update: we do need to support either input being zero :/) – Peter Cordes – 2016-04-09T19:25:45.107

For Thumb2, there's an ite instruction: if-then-else. Should be perfect for cmp / sub one way / sub the other way. – Peter Cordes – 2016-04-09T23:23:47.410

2

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

Jeto

Posted 2016-04-07T05:29:54.567

Reputation: 1 601

Does not work correctly if one of inputs is zero. – Egor Skriptunoff – 2016-04-10T14:05:09.460

This should save you a few SELECT MAX(LEVEL)FROM DUAL WHERE MOD(:1,LEVEL)+MOD(:2,LEVEL)=0 CONNECT BY LEVEL<=:1+:2; – MickyT – 2016-04-10T23:50:55.200

2

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

Sok

Posted 2016-04-07T05:29:54.567

Reputation: 5 592

2

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.

DSkoog

Posted 2016-04-07T05:29:54.567

Reputation: 560

2

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

rnso

Posted 2016-04-07T05:29:54.567

Reputation: 1 635

Built-ins are disallowed in the challenge specification. – rturnbull – 2016-10-04T14:02:15.677

I have corrected the answer. – rnso – 2016-10-04T16:32:19.620

2

Logy, 64 23 bytes (non-competing)

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

TuxCrafting

Posted 2016-04-07T05:29:54.567

Reputation: 4 547

2

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

NonlinearFruit

Posted 2016-04-07T05:29:54.567

Reputation: 5 334

2

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

rturnbull

Posted 2016-04-07T05:29:54.567

Reputation: 3 689

1"if" rather than ifelse for -2 bytes, but you lose the vectorization... – Giuseppe – 2017-09-05T02:29:18.097

@Giuseppe Thanks, good catch! – rturnbull – 2017-09-06T22:15:46.473

2

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.

Titus

Posted 2016-04-07T05:29:54.567

Reputation: 13 814

1

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.

JPeroutek

Posted 2016-04-07T05:29:54.567

Reputation: 734

1

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

Bubbler

Posted 2016-04-07T05:29:54.567

Reputation: 16 616

1

Mathematica, 27 bytes

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

Not much to see here.

LegionMammal978

Posted 2016-04-07T05:29:54.567

Reputation: 15 731

Hey, I was going to post that! (No I wasn't, I didn't know that GCD existed.) – CalculatorFeline – 2016-04-07T22:51:29.437

2-1 LCMGCD. – CalculatorFeline – 2016-04-08T02:30:51.473

1Built-ins for GCD and LCM are disallowed. – mbomb007 – 2016-10-04T14:40:20.970

@LegionMammal978 And? Now it's invalid. Aka, delete it or fix it. – mbomb007 – 2016-10-04T22:49:11.573

1

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)

Mego

Posted 2016-04-07T05:29:54.567

Reputation: 32 998

1

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

Bald Bantha

Posted 2016-04-07T05:29:54.567

Reputation: 463

You can save a byte with currying. – Cyoce – 2016-04-09T08:01:17.647

Unfortunately, this doesn't work with the new test cases (in particular, 0, 2). – Dennis – 2016-04-09T18:05:34.323

What is currying? – Bald Bantha – 2016-04-10T19:24:15.453

Dennis, 0 / 2 != 2. I say the test cases are wrong... sneaky face – Bald Bantha – 2016-04-10T19:25:34.727

1

Scheme, 44 bytes

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

Scheme is the future of code-golf. :)

Numeri says Reinstate Monica

Posted 2016-04-07T05:29:54.567

Reputation: 151

1

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

Mama Fun Roll

Posted 2016-04-07T05:29:54.567

Reputation: 7 234

1

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 |

MT0

Posted 2016-04-07T05:29:54.567

Reputation: 3 373

1

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 

MT0

Posted 2016-04-07T05:29:54.567

Reputation: 3 373

1

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)

miles

Posted 2016-04-07T05:29:54.567

Reputation: 15 654

1

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

Kevin Cruijssen

Posted 2016-04-07T05:29:54.567

Reputation: 67 575

0

Befunge-93, 21 bytes

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

Try it Online

Yet another Euclidean algorithm

Jo King

Posted 2016-04-07T05:29:54.567

Reputation: 38 234

0

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

RosLuP

Posted 2016-04-07T05:29:54.567

Reputation: 3 036

0

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

Oliver

Posted 2016-04-07T05:29:54.567

Reputation: 7 160

0

Ink, 29 bytes

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

Try it online!

Sara J

Posted 2016-04-07T05:29:54.567

Reputation: 2 576

0

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

RosLuP

Posted 2016-04-07T05:29:54.567

Reputation: 3 036

0

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

Leandro Caniglia

Posted 2016-04-07T05:29:54.567

Reputation: 181

Feel free to expand your answer by including an explanation and a link to an online interpreter. Not everyone here knows Smalltalk. When your answers are short and just code, they show in the "Low Quality Posts" queue and users have to review them. Take a look at answers by other users to see some examples. – mbomb007 – 2019-03-19T15:11:06.407

@mbomb007 Done. Thanks for the suggestion. – Leandro Caniglia – 2019-03-19T15:39:00.167

0

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.

Robert Benson

Posted 2016-04-07T05:29:54.567

Reputation: 1 339

0

Perl 6, 28 bytes

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

bb94

Posted 2016-04-07T05:29:54.567

Reputation: 1 831

0

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

reffu

Posted 2016-04-07T05:29:54.567

Reputation: 1 361

0

Pyth, 2 bytes

iE

Try it here!

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

Denker

Posted 2016-04-07T05:29:54.567

Reputation: 6 639

Haha, I like it. – Mike Shlanta – 2016-04-07T18:06:40.117

2If you change the input format, iF also works. In addition, I think M?HgH%GHG is the shortest no-builtin way of doing this. – FryAmTheEggman – 2016-04-07T19:39:57.813

7I think the question disallows using a GCD builtin. – Cyoce – 2016-04-09T23:10:11.313