Greatest common divisor: Difference between revisions

Add bruijn
(Add bruijn)
 
(104 intermediate revisions by 35 users not shown)
Line 23:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F gcd(=u, =v)
L v != 0
(u, v) = (v, u % v)
Line 35:
print(gcd(-6, 9))
print(gcd(8, 45))
print(gcd(40902, 24140))</langsyntaxhighlight>
 
{{out}}
Line 53:
For maximum compatibility, this program uses only the basic instruction set (S/360)
with 2 ASSIST macros (XDECO,XPRNT).
<langsyntaxhighlight lang="360asm">* Greatest common divisor 04/05/2016
GCD CSECT
USING GCD,R15 use calling register
Line 84:
XDEC DS CL12 temp for edit
YREGS
END GCD</langsyntaxhighlight>
{{out}}
<pre>
gcd( 1071, 1029)= 21
</pre>
 
=={{header|PowerPC Assembly}}==
Compile with:
<pre>
gcc -mbig -mregnames -nostartfiles -nodefaultlibs -o gcd gcd.S
</pre>
 
<syntaxhighlight lang="asm" line="1">
#include <syscall.h>
_gcd_string:
.ascii "gcd("
_gcd_string_len = . - _gcd_string
_gcd_close_string:
.ascii ") = "
_gcd_close_string_len = . - _gcd_close_string
 
.equiv STDIN, 0
.equiv STDOUT, 1
 
.align 4
.section ".text"
.global _start
.section ".opd","aw"
.align 3
_start:
.quad ._start,.TOC.@tocbase,0
.previous
.global ._start
._start:
li r30, 1071
li r31, 1029
# move the loaded values into the argument registers
mr r3, r30
mr r4, r31
bl gcd
# save the result for printing later
mr r29, r3
addis r4, r2, _gcd_string@toc@ha
addi r4, r4, _gcd_string@toc@l
li r5, _gcd_string_len
bl print_string
mr r3, r30
bl print_integer
li r3, ','
bl print_char
mr r3, r31
bl print_integer
addis r4, r2, _gcd_close_string@toc@ha
addi r4, r4, _gcd_close_string@toc@l
li r5, _gcd_close_string_len
bl print_string
mr r3, r29
bl print_integer
li r3, '\n'
bl print_char
li r0,SYS_exit # syscall number (sys_exit)
li r3,0 # first argument: exit code
sc # call kernel
 
gcd:
cmpd r3, r4
bge _gcd
mr r5, r3
mr r3, r4
mr r4, r5
_gcd:
cmpdi r4, 0
beqlr
mr r5, r3
mr r3, r4
modud r4, r5, r4
b _gcd
 
# r4 is the address of the string
# r5 is the length of the string
print_string:
li r0, SYS_write
li r3, STDOUT
sc
blr
 
print_char:
mr r4, r3
li r0, SYS_write
li r3, STDOUT
stb r4, -1(sp)
addi r4, sp, -1
li r5, 1
sc
blr
 
print_integer:
# r3 is the integer to print
# r4 is the working register
# r5 holds the current address to write to the string
# r6 is 10 for division operations
# r7 is working storage
mr r5, sp
li r6, 10
neg r4, r3
cmpdi r3, 0
bne 1f
li r7, '0'
stbu r7, -1(r5)
b 3f
1:
isellt r4, r4, r3 # r4 = abs(r3)
1:
modsd r7, r4, r6
divd r4, r4, r6
addi r7, r7, '0'
stbu r7, -1(r5)
cmpdi r4, 0
beq 1f
b 1b
 
1:
cmpdi r3, 0
blt 2f
3:
mr r4, r5
subf r5, r5, sp
mflr r14
bl print_string
mtlr r14
blr
 
2:
li r7, '-'
stbu r7, -1(r5)
b 3b
</syntaxhighlight>
 
{{out}}
<pre>
gcd(1071,1029) = 21
</pre>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">: gcd \ a b -- gcd
dup 0 n:= if drop ;; then
tuck \ b a b
Line 105 ⟶ 242:
 
bye
</syntaxhighlight>
</lang>
{{out}}
<pre>GCD of 5 and 100 = 5
Line 113 ⟶ 250:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program calPgcd64.s */
Line 256 ⟶ 393:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
 
(defun gcd$ (x y)
Line 265 ⟶ 402:
nil)
((zp y) x)
(t (gcd$ y (mod x y)))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">CARD FUNC Gcd(CARD a,b)
CARD tmp
 
Line 296 ⟶ 433:
Test(123,1)
Test(0,0)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Greatest_common_divisor.png Screenshot from Atari 8-bit computer]
Line 308 ⟶ 445:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">//Euclidean algorithm
function gcd(a:int,b:int):int
{
Line 327 ⟶ 464:
}
return a;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Gcd_Test is
Line 350 ⟶ 487:
Put_Line("GCD of 5, 100 is" & Integer'Image(Gcd(5, 100)));
Put_Line("GCD of 7, 23 is" & Integer'Image(Gcd(7, 23)));
end Gcd_Test;</langsyntaxhighlight>
 
Output:
Line 360 ⟶ 497:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">o_integer(gcd(33, 77));
o_byte('\n');
o_integer(gcd(49865, 69811));
o_byte('\n');</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
<langsyntaxhighlight lang="algol60">begin
comment Greatest common divisor - algol 60;
Line 390 ⟶ 527:
outinteger(1,gcd(21,35))
end
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 402 ⟶ 539:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">PROC gcd = (INT a, b) INT: (
IF a = 0 THEN
b
Line 418 ⟶ 555:
INT c = 49865, d = 69811;
printf(($x"The gcd of"g" and "g" is "gl$,c,d,gcd(c,d)))
)</langsyntaxhighlight>
Output:
<pre>
Line 426 ⟶ 563:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algol">BEGIN
 
% RETURN P MOD Q %
Line 457 ⟶ 594:
COMMENT - EXERCISE THE FUNCTION;
 
WRITE("THE GDCGCD OF 21 AND 35 IS", GCD(21,35));
WRITE("THE GDCGCD OF 23 AND 35 IS", GCD(23,35));
WRITE("THE GDCGCD OF 1071 AND 1029 IS", GCD(1071,1029));
WRITE("THE GDCGCD OF 3528 AND 3780 IS", GCD(3528,252));
 
END</langsyntaxhighlight>
{{out}}
<pre>THE GDCGCD OF 21 AND 35 IS 7
THE GDCGCD OF 23 AND 35 IS 1
THE GDCGCD OF 1071 AND 1029 IS 21
THE GDCGCD OF 3528 AND 3780 IS 252
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% iterative Greatest Common Divisor routine %
integer procedure gcd ( integer value m, n ) ;
Line 478 ⟶ 615:
a := abs( m );
b := abs( n );
ifwhile ab not = 0 thendo begin
newA := b;
endb := a rem b;
else begin a := newA;
while b not = 0 do beginend;
newA := b;a
b := a rem b;
a := newA;
end;
a
end
end gcd ;
 
write( gcd( -21, 35 ) );
end.</lang>
</syntaxhighlight>
 
=={{header|Alore}}==
 
<langsyntaxhighlight Alorelang="alore">def gcd(a as Int, b as Int) as Int
while b != 0
a,b = b, a mod b
end
return Abs(a)
end</langsyntaxhighlight>
 
=={{header|AntLang}}==
AntLang has a built-in gcd function.
<syntaxhighlight lang AntLang="antlang">gcd[33; 77]</langsyntaxhighlight>
 
It is not recommended, but possible to implement it on your own.
<langsyntaxhighlight AntLanglang="antlang">/Unoptimized version
gcd':{a:x;b:y;last[{(0 eq a mod x) min (0 eq b mod x)} hfilter {1 + x} map range[a max b]]}</langsyntaxhighlight>
 
=={{header|APL}}==
Line 528 ⟶ 661:
By recursion:
 
<langsyntaxhighlight AppleScriptlang="applescript">-- gcd :: Int -> Int -> Int
on gcd(a, b)
if b ≠ 0 then
Line 540 ⟶ 673:
end if
end gcd
</syntaxhighlight>
</lang>
 
And just for the sake of it, the same thing iteratively:
 
<langsyntaxhighlight lang="applescript">on hcf(a, b)
repeat until (b = 0)
set x to a
Line 553 ⟶ 686:
if (a < 0) then return -a
return a
end hcf</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>0 A = ABS(INT(A))
1 B = ABS(INT(B))
2 GCD = A * NOT NOT B
3 FOR B = B + A * NOT B TO 0 STEP 0
4 A = GCD
5 GCD = B
6 B = A - INT (A / GCD) * GCD
7 NEXT B</lang>
=={{header|Arendelle}}==
<pre>&lt; a , b &gt;
Line 584 ⟶ 708:
 
=={{header|Arturo}}==
<syntaxhighlight lang ="rebol">print gcd [10 15]</langsyntaxhighlight>
 
{{out}}
Line 593 ⟶ 717:
{{works with|ATS|Postiats 0.4.1}}
 
You can compile with as simple a command as ‘patscc -o gcd gcd.dats’, although
ATS code really likes to have you turn on the C compiler’s optimizations.
For example, ‘patscc -O3 -march=native -o gcd gcd.dats’
 
===Stein’s algorithm, without proofs===
<lang ats>(********************************************************************)
 
 
Here is an implementation of Stein’s algorithm, without proofs of termination or correctness.
 
<syntaxhighlight lang="ats">(********************************************************************)
(*
 
GCD of two positive integers, by Stein’s algorithm:
https://en.wikipedia.org/w/index.php?title=Binary_GCD_algorithm&oldid=1072393147
 
This is an implementation without proofproofs of correctness, althoughanything.
I do also show some proofs about the gcd.
 
The implementations shown here require the GCC builtin functions
Line 610 ⟶ 735:
that supports those functions, you are fine. Otherwise, one could
easily substitute other C code.
 
Compile with ‘patscc -o gcd gcd.dats’.
 
*)
Line 621 ⟶ 748:
(********************************************************************)
(* *)
(* ForDeclarations of the sakefunctions. of interest, here is a tiny bit of proof work *)
(* about the gcd. *)
(* *)
 
(* g0uint_gcd_stein will be the generic template function for
(* Definition of the gcd by Euclid’s algorithm, using subtractions;
unsigned integers. *)
gcd(0,0) is defined to equal zero. (I do not prove that this
extern fun {tk : tkind}
definition is equivalent to ‘greatest common divisor’; that’s not a
g0uint_gcd_stein :
sort of thing ATS is good at.) *)
(g0uint tk, g0uint tk) -<> g0uint tk
dataprop GCD (int, int, int) =
| GCD_0_0 (0, 0, 0)
| {u : pos}
GCD_u_0 (u, 0, u)
| {v : pos}
GCD_0_v (0, v, v)
| {u, v : pos | u <= v}
{d : pos}
GCD_u_le_v (u, v, d) of
GCD (u, v - u, d)
| {u, v : pos | u > v}
{d : pos}
GCD_u_gt_v (u, v, d) of
GCD (u - v, v, d)
| {u, v : int | u < 0 || v < 0}
{d : pos}
GCD_u_or_v_neg (u, v, d) of
GCD (abs u, abs v, d)
 
(* g0int_gcd_stein will be the generic template function for
(* Here is a proof, by construction, that the gcd of 12 and 8 is 4. *)
signed integers, giving an unsigned result. *)
prfn
extern fun {tk_signed, tk_unsigned : tkind}
gcd_12_8 () :<prf>
g0int_gcd_stein :
GCD (12, 8, 4) =
(g0int tk_signed, g0int tk_signed) -<> g0uint tk_unsigned
let
prval pf = GCD_u_0 {4} ()
prval pf = GCD_u_le_v {4, 4} {4} (pf)
prval pf = GCD_u_le_v {4, 8} {4} (pf)
prval pf = GCD_u_gt_v {12, 8} {4} (pf)
in
pf
end
 
(* Let us call these functions ‘gcd_stein’ or just ‘gcd’. *)
(* A lemma: the gcd is total. That is, it is defined for all
overload gcd_stein with g0uint_gcd_stein
integers. *)
overload gcd_stein with g0int_gcd_stein
extern prfun
overload gcd with gcd_stein
gcd_istot :
{u, v : int}
() -<prf>
[d : int]
GCD (u, v, d)
 
(********************************************************************)
(* Another lemma: the gcd is a function: it has a unique value for
(* *)
any given pair of arguments. *)
(* The implementations. *)
extern prfun
(* *)
gcd_isfun :
{u, v : int}
{d, e : int}
(GCD (u, v, d),
GCD (u, v, e)) -<prf>
[d == e] void
 
%{^
(* Proof of gcd_istot. This source file cannot be compiled unless the
 
proof is valid. *)
/*
primplement
 
gcd_istot {u, v} () =
We will need a ‘count trailing zeros of a positive number’ function,
but this is not provided in the ATS prelude. Here are
implementations using GCC builtin functions. For fast alternatives
in standard C, see
https://www.chessprogramming.org/index.php?title=BitScan&oldid=22495#Trailing_Zero_Count
 
*/
 
ATSinline() atstype_uint
rosettacode_gcd_g0uint_ctz_uint (atstype_uint x)
{
return __builtin_ctz (x);
}
 
ATSinline() atstype_ulint
rosettacode_gcd_g0uint_ctz_ulint (atstype_ulint x)
{
return __builtin_ctzl (x);
}
 
ATSinline() atstype_ullint
rosettacode_gcd_g0uint_ctz_ullint (atstype_ullint x)
{
return __builtin_ctzll (x);
}
 
%}
 
extern fun g0uint_ctz_uint : uint -<> int = "mac#%"
extern fun g0uint_ctz_ulint : ulint -<> int = "mac#%"
extern fun g0uint_ctz_ullint : ullint -<> int = "mac#%"
 
(* A generic template function for ‘count trailing zeros’ of
non-dependent unsigned integers. *)
extern fun {tk : tkind} g0uint_ctz : g0uint tk -<> int
 
(* Link the implementations to the template function. *)
implement g0uint_ctz<uint_kind> (x) = g0uint_ctz_uint x
implement g0uint_ctz<ulint_kind> (x) = g0uint_ctz_ulint x
implement g0uint_ctz<ullint_kind> (x) = g0uint_ctz_ullint x
 
(* Let one call the function simply ‘ctz’. *)
overload ctz with g0uint_ctz
 
(* Now the actual implementation of g0uint_gcd_stein, the template
function for the gcd of two unsigned integers. *)
implement {tk}
g0uint_gcd_stein (u, v) =
let
(* Make ‘t’ a shorthand for the unsigned integer type. *)
prfun
typedef t = g0uint tk
gcd_istot__nat_nat__ {u, v : nat | u != 0 || v != 0} .<u + v>.
() :<prf> [d : pos] GCD (u, v, d) =
sif v == 0 then
GCD_u_0 ()
else sif u == 0 then
GCD_0_v ()
else sif u <= v then
GCD_u_le_v (gcd_istot__nat_nat__ {u, v - u} ())
else
GCD_u_gt_v (gcd_istot__nat_nat__ {u - v, v} ())
 
(* Use this macro to fake proof that an int is non-negative. *)
prfun
macdef nonneg (n) = $UNSAFE.cast{intGte 0} ,(n)
gcd_istot__int_int__ {u, v : int | u != 0 || v != 0} .<>.
 
() :<prf> [d : pos] GCD (u, v, d) =
(* Looping sifis udone <by 0tail ||recursion. vThere <is 0no thenproof
the function terminates; this fact is indicated by
GCD_u_or_v_neg (gcd_istot__nat_nat__ {abs u, abs v} ())
else ‘<!ntm>’. *)
fun {tk : tkind}
gcd_istot__nat_nat__ {u, v} ()
main_loop (x_odd : t, y : t) :<!ntm> t =
let
(* Remove twos from y, giving an odd number.
Note gcd(x_odd,y_odd) = gcd(x_odd,y). *)
val y_odd = (y >> nonneg (ctz y))
in
if x_odd = y_odd then
x_odd
else
let
(* If y_odd < x_odd then swap x_odd and y_odd.
This operation does not affect the gcd. *)
val x_odd = min (x_odd, y_odd)
and y_odd = max (x_odd, y_odd)
in
main_loop (x_odd, y_odd - x_odd)
end
end
 
fn
u_and_v_both_positive (u : t, v : t) :<> t =
let
(* n = the number of common factors of two in u and v. *)
val n = ctz (u lor v)
 
(* Remove the common twos from u and v, giving x and y. *)
val x = (u >> nonneg n)
val y = (v >> nonneg n)
 
(* Remove twos from x, giving an odd number.
Note gcd(x_odd,y) = gcd(x,y). *)
val x_odd = (x >> nonneg (ctz x))
 
(* Run the main loop, but pretend it is proven to
terminate. Otherwise we could not write ‘<>’ above,
telling the ATS compiler that we trust the function
to terminate. *)
val z = $effmask_ntm (main_loop (x_odd, y))
in
(* Put the common factors of two back in. *)
(z << nonneg n)
end
 
(* If v < u then swap u and v. This operation does not
affect the gcd. *)
val u = min (u, v)
and v = max (u, v)
in
sifif iseqz u == 0 && v == 0 then
GCD_0_0 ()v
else
gcd_istot__int_int__u_and_v_both_positive {(u, v} ()
end
 
(* The implementation of g0int_gcd_stein, the template function for
(* Proof of gcd_isfun. This source file cannot be compiled unless the
the gcd of two signed integers, giving an unsigned result. *)
proof is valid. *)
implement {signed_tk, unsigned_tk}
primplement
g0int_gcd_stein (u, v) =
gcd_isfun {u, v} {d, e} (pfd, pfe) =
let
val abs_u = $UNSAFE.cast{g0uint unsigned_tk} (abs u)
prfun
val abs_v = $UNSAFE.cast{g0uint unsigned_tk} (abs v)
gcd_isfun__nat_nat__ {u, v : nat}
{d, e : int}
.<u + v>.
(pfd : GCD (u, v, d),
pfe : GCD (u, v, e)) :<prf> [d == e] void =
case+ pfd of
| GCD_0_0 () =>
{
prval GCD_0_0 () = pfe
}
| GCD_u_0 () =>
{
prval GCD_u_0 () = pfe
}
| GCD_0_v () =>
{
prval GCD_0_v () = pfe
}
| GCD_u_le_v pfd1 =>
{
prval GCD_u_le_v pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
| GCD_u_gt_v pfd1 =>
{
prval GCD_u_gt_v pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
in
g0uint_gcd_stein<unsigned_tk> (abs_u, abs_v)
sif u < 0 || v < 0 then
{
prval GCD_u_or_v_neg pfd1 = pfd
prval GCD_u_or_v_neg pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
else
gcd_isfun__nat_nat__ (pfd, pfe)
end
 
(********************************************************************)
(* A demonstration program. *)
 
implement
main0 () =
begin
(* Unsigned integers. *)
assertloc (gcd (0U, 10U) = 10U);
assertloc (gcd (9UL, 6UL) = 3UL);
assertloc (gcd (40902ULL, 24140ULL) = 34ULL);
 
(* Signed integers. *)
assertloc (gcd (0, 10) = gcd (0U, 10U));
assertloc (gcd (~10, 0) = gcd (0U, 10U));
assertloc (gcd (~6L, ~9L) = 3UL);
assertloc (gcd (40902LL, 24140LL) = 34ULL);
assertloc (gcd (40902LL, ~24140LL) = 34ULL);
assertloc (gcd (~40902LL, 24140LL) = 34ULL);
assertloc (gcd (~40902LL, ~24140LL) = 34ULL);
assertloc (gcd (24140LL, 40902LL) = 34ULL);
assertloc (gcd (~24140LL, 40902LL) = 34ULL);
assertloc (gcd (24140LL, ~40902LL) = 34ULL);
assertloc (gcd (~24140LL, ~40902LL) = 34ULL)
end
 
(********************************************************************)</syntaxhighlight>
 
 
===Stein’s algorithm, with proof of termination===
 
Here is an implementation of Stein’s algorithm, this time with a proof of termination. Notice that the proof is rather ‘informal’; this is practical systems programming, not an exercise in mathematical logic.
 
<syntaxhighlight lang="ats">(********************************************************************)
(*
 
GCD of two integers, by Stein’s algorithm:
https://en.wikipedia.org/w/index.php?title=Binary_GCD_algorithm&oldid=1072393147
 
This is an implementation with proof of termination.
 
The implementations shown here require the GCC builtin functions
for ‘count trailing zeros’. If your C compiler is GCC or another
that supports those functions, you are fine. Otherwise, one could
easily substitute other C code.
 
Compile with ‘patscc -o gcd gcd.dats’.
 
*)
 
#define ATS_EXTERN_PREFIX "rosettacode_gcd_"
#define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)
 
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
 
(********************************************************************)
(* *)
(* Now declarationsDeclarations of the actual, executable functions. *)
(* *)
 
(* g0uint_gcd_steing1uint_gcd_stein will be the generic template function for
unsigned integers. *)
extern fun {tk : tkind}
Line 836 ⟶ 1,036:
g0uint_gcd_stein (u, v) =
let
(* Make ‘t’ a shorthand for the unsigned integer typetypes. *)
typedef t = g0uint tk
typedef t (i : int) = g1uint (tk, i)
 
(* Use this macro to fake proof that an int is non-negative. *)
macdef nonneg (n) = $UNSAFE.cast{intGte 0} ,(n)
 
(* Looping is done by tail recursion. ThereThe isvalue noof proof(x_odd + y)
themust functiondecrease terminates;towards thiszero, isto indicatedprove by ‘<!ntm>’termination. *)
fun {tk : tkind}
main_loop (x : t{x_odd, y : t)pos} :.<!ntm>x_odd t+ =y>.
(x_odd : t (x_odd), y : t (y)) :<>
[d : pos] t (d) =
let
 
(* Remove twos from y, giving an odd number y1. *)
val(* y1Remove =twos from (y, >>giving nonnegan (ctzodd y))number. Note
gcd(x_odd,y_odd) = gcd(x_odd,y). We do not have a
dependent-type version of the following operation, so let
us do it with non-dependent types. *)
val [y_odd : int] y_odd =
g1ofg0 ((g0ofg1 y) >> nonneg (ctz (g0ofg1 y)))
 
(* Assert some things we know without proof. (You could also
use assertloc, which inserts a runtime check.) *)
prval _ = $UNSAFE.prop_assert {0 < y_odd} ()
prval _ = $UNSAFE.prop_assert {y_odd <= y} ()
in
if xx_odd = y1y_odd then
xx_odd
else if y_odd < x_odd then
main_loop (y_odd, x_odd - y_odd)
else
letmain_loop (x_odd, y_odd - x_odd)
(* Swap x and y1 if necessary, renaming them p and q.
Perhaps the C compiler can convert the computation of
p and q to branchless instructions. Notice that the
ATS compiler needed a hint that the values of p and q
were of type t. *)
val p = (if x < y1 then x else y1) : t
val q = (if x < y1 then y1 else x)
in
main_loop (p, q - p)
end
end
 
Line 876 ⟶ 1,081:
val y = (v >> nonneg n)
 
(* Remove twos from x, giving an odd number. *)
Note gcd(x_odd,y) = gcd(x,y). *)
val x_odd = (x >> nonneg (ctz x))
 
(* RunTo theprove maintermination loopof main_loop, but pretend it iswe provenhave to
terminate.convert Otherwisex_odd weand couldy notto writea ‘<>’dependent type. above,*)
val [x_odd : tellingint] thex_odd ATS= compilerg1ofg0 that we trust the functionx_odd
val [y : toint] terminate.y *)= g1ofg0 y
 
val z = $effmask_ntm (main_loop (x_odd, y))
(* Assert that they are positive. (One could also use
assertloc, which inserts a runtime check.) *)
prval _ = $UNSAFE.prop_assert {0 < x_odd} ()
prval _ = $UNSAFE.prop_assert {0 < y} ()
 
val z = main_loop (x_odd, y)
 
(* Convert back to the non-dependent type. *)
val z = g0ofg1 z
in
(* Put the common factors of two back in. *)
(z << nonneg n)
end
 
(* If v < u then swap u and v. This operation does not
affect the gcd. *)
val u = min (u, v)
and v = max (u, v)
in
if iseqz u then
v
else if iseqz v then
u
else if u = v then
u
else
u_and_v_both_positive (u, v)
Line 924 ⟶ 1,141:
assertloc (gcd (~10, 0) = gcd (0U, 10U));
assertloc (gcd (~6L, ~9L) = 3UL);
assertloc (gcd (40902LL, ~24140LL) = 34ULL);
assertloc (gcd (40902LL, ~24140LL) = 34ULL);
assertloc (gcd (~40902LL, 24140LL) = 34ULL);
assertloc (gcd (~40902LL, ~24140LL) = 34ULL);
assertloc (gcd (24140LL, 40902LL) = 34ULL);
assertloc (gcd (~24140LL, 40902LL) = 34ULL);
assertloc (gcd (24140LL, ~40902LL) = 34ULL);
assertloc (gcd (~24140LL, ~40902LL) = 34ULL)
end
 
(********************************************************************)</langsyntaxhighlight>
 
===Euclid’s algorithm, with proof of termination and correctness===
 
Here is an implementation of Euclid’s algorithm, with a proof of correctness.
 
<syntaxhighlight lang="ats">(********************************************************************)
(*
 
GCD of two integers, by Euclid’s algorithm; verified with proofs.
 
Compile with ‘patscc -o gcd gcd.dats’.
 
*)
 
#define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)
 
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
 
(********************************************************************)
(* *)
(* Definition of the gcd by axioms in the static language. *)
(* *)
(* (‘Props’ are better supported in ATS, but I enjoy using the *)
(* the static language in proofs.) *)
(* *)
 
(* Write the gcd as an undefined static function. It will be defined
implicitly by axioms. (Such a function also can be used with an
external SMT solver such as CVC4, but using an external solver is
not the topic of this program.) *)
stacst gcd (u : int, v : int) : int
 
(*
I think the reader will accept the following axioms as valid,
if gcd(0, 0) is to be defined as equal to zero.
 
(An exercise for the reader is to prove ‘gcd_of_remainder’
from gcd (u, v) == gcd (u, v - u). This requires definitions
of multiplication and Euclidean division, which are encoded
in terms of props in ‘prelude/SATS/arith_prf.sats’.)
*)
 
extern praxi
gcd_of_zero :
{u, v : int | u == 0; 0 <= v} (* For all integers u = 0,
v non-negative. *)
() -<prf> [gcd (u, v) == v] void
 
extern praxi
gcd_of_remainder :
{u, v : int | 0 < u; 0 <= v} (* For all integers u positive,
v non-negative. *)
() -<prf> [gcd (u, v) == gcd (u, v mod u)] void
 
extern praxi
gcd_is_commutative :
{u, v : int} (* For all integers u, v. *)
() -<prf> [gcd (u, v) == gcd (v, u)] void
 
extern praxi
gcd_of_the_absolute_values :
{u, v : int} (* For all integers u, v. *)
() -<prf> [gcd (u, v) == gcd (abs u, abs v)] void
 
extern praxi
gcd_is_a_function :
{u1, v1 : int}
{u2, v2 : int | u1 == u2; v1 == v2}
() -<prf> [gcd (u1, v1) == gcd (u2, v2)] void
 
(********************************************************************)
(* *)
(* Function declarations. *)
(* *)
 
(* g1uint_gcd_euclid will be the generic template function for
unsigned integers. *)
extern fun {tk : tkind}
g1uint_gcd_euclid :
{u, v : int}
(g1uint (tk, u),
g1uint (tk, v)) -<>
g1uint (tk, gcd (u, v))
 
(* g1int_gcd_euclid will be the generic template function for
signed integers, giving an unsigned result. *)
extern fun {tk_signed, tk_unsigned : tkind}
g1int_gcd_euclid :
{u, v : int}
(g1int (tk_signed, u),
g1int (tk_signed, v)) -<>
g1uint (tk_unsigned, gcd (u, v))
 
(* Let us call these functions ‘gcd_euclid’ or just ‘gcd’. *)
overload gcd_euclid with g1uint_gcd_euclid
overload gcd_euclid with g1int_gcd_euclid
overload gcd with gcd_euclid
 
(********************************************************************)
(* *)
(* Function implementations. *)
(* *)
 
(* The implementation of the remainder function in the ATS2 prelude
is inconvenient for us; it does not say that the result equals
‘u mod v’. Let us reimplement it more to our liking. *)
fn {tk : tkind}
g1uint_rem {u, v : int | v != 0}
(u : g1uint (tk, u),
v : g1uint (tk, v)) :<>
[w : int | 0 <= w; w < v; w == u mod v]
g1uint (tk, w) =
let
prval _ = lemma_g1uint_param u
prval _ = lemma_g1uint_param v
in
$UNSAFE.cast (g1uint_mod (u, v))
end
 
implement {tk}
g1uint_gcd_euclid {u, v} (u, v) =
let
(* The static variable v, which is defined within the curly
braces, must, with each iteration, approach zero without
passing it. Otherwise the loop is not proven to terminate,
and the typechecker will reject it. *)
fun
loop {u, v : int | 0 <= u; 0 <= v} .<v>.
(u : g1uint (tk, u),
v : g1uint (tk, v)) :<>
g1uint (tk, gcd (u, v)) =
if v = g1i2u 0 then
let
(* prop_verify tests whether what we believe we have
proven has actually been proven. Using it a lot lengthens
the code but is excellent documentation. *)
prval _ = prop_verify {0 <= u} ()
prval _ = prop_verify {v == 0} ()
 
prval _ = gcd_of_zero {v, u} ()
prval _ = prop_verify {gcd (v, u) == u} ()
 
prval _ = gcd_is_commutative {u, v} ()
prval _ = prop_verify {gcd (u, v) == gcd (v, u)} ()
 
(* Therefore, by transitivity of equality: *)
prval _ = prop_verify {gcd (u, v) == u} ()
in
u
end
else
let
prval _ = prop_verify {0 <= u} ()
prval _ = prop_verify {0 < v} ()
 
prval _ = gcd_of_remainder {v, u} ()
prval _ = prop_verify {gcd (v, u) == gcd (v, u mod v)} ()
 
prval _ = gcd_is_commutative {u, v} ()
prval _ = prop_verify {gcd (u, v) == gcd (v, u)} ()
 
(* Therefore, by transitivity of equality: *)
prval _ = prop_verify {gcd (u, v) == gcd (v, u mod v)} ()
 
val [w : int] w = g1uint_rem (u, v)
prval _ = prop_verify {0 <= w} ()
prval _ = prop_verify {w < v} ()
prval _ = prop_verify {w == u mod v} ()
 
(* It has been proven that the function will terminate: *)
prval _ = prop_verify {0 <= w && w < v} ()
 
prval _ = gcd_is_a_function {v, u mod v} {v, w} ()
prval _ = prop_verify {gcd (v, u mod v) == gcd (v, w)} ()
 
(* Therefore, by transitivity of equality: *)
prval _ = prop_verify {gcd (u, v) == gcd (v, w)} ()
in
loop (v, w)
end
 
(* u is unsigned, thus proving 0 <= u. *)
prval _ = lemma_g1uint_param (u)
 
(* v is unsigned, thus proving 0 <= v. *)
prval _ = lemma_g1uint_param (v)
in
loop (u, v)
end
 
implement {tk_signed, tk_unsigned}
g1int_gcd_euclid {u, v} (u, v) =
let
(* Prove that gcd(abs u, abs v) equals gcd(u, v). *)
prval _ = gcd_of_the_absolute_values {u, v} ()
in
(* Compute gcd(abs u, abs v). The ‘g1i2u’ notations cast the
values from signed integers to unsigned integers. *)
g1uint_gcd_euclid (g1i2u (abs u), g1i2u (abs v))
end
 
(********************************************************************)
(* *)
(* A demonstration program. *)
(* *)
(* Unfortunately, the ATS prelude may not include implementations *)
(* of all the functions we need for long and long long integers. *)
(* Thus the demonstration will be entirely on regular int and uint. *)
(* *)
(* (Including implementations here would distract from the purpose. *)
(* *)
 
implement
main0 () =
begin
(* Unsigned integers. *)
assertloc (gcd (0U, 10U) = 10U);
assertloc (gcd (9U, 6U) = 3U);
assertloc (gcd (40902U, 24140U) = 34U);
 
(* Signed integers. *)
assertloc (gcd (0, 10) = gcd (0U, 10U));
assertloc (gcd (~10, 0) = gcd (0U, 10U));
assertloc (gcd (~6, ~9) = 3U);
assertloc (gcd (40902, 24140) = 34U);
assertloc (gcd (40902, ~24140) = 34U);
assertloc (gcd (~40902, 24140) = 34U);
assertloc (gcd (~40902, ~24140) = 34U);
assertloc (gcd (24140, 40902) = 34U);
assertloc (gcd (~24140, 40902) = 34U);
assertloc (gcd (24140, ~40902) = 34U);
assertloc (gcd (~24140, ~40902) = 34U)
end
 
(********************************************************************)</syntaxhighlight>
 
===Some proofs about the gcd===
 
 
For the sake of interest, here is some use of ATS's "props"-based proof system. There is no executable code in the following.
 
<syntaxhighlight lang="ats">(* Typecheck this file with ‘patscc -tcats gcd-proofs.dats’. *)
 
(* Definition of the gcd by Euclid’s algorithm, using subtractions;
gcd(0,0) is defined to equal zero. (I do not prove that this
definition is equivalent to the common meaning of ‘greatest common
divisor’; that’s not a sort of thing ATS is good at.) *)
dataprop GCD (int, int, int) =
| GCD_0_0 (0, 0, 0)
| {u : pos}
GCD_u_0 (u, 0, u)
| {v : pos}
GCD_0_v (0, v, v)
| {u, v : pos | u <= v}
{d : pos}
GCD_u_le_v (u, v, d) of
GCD (u, v - u, d)
| {u, v : pos | u > v}
{d : pos}
GCD_u_gt_v (u, v, d) of
GCD (u - v, v, d)
| {u, v : int | u < 0 || v < 0}
{d : pos}
GCD_u_or_v_neg (u, v, d) of
GCD (abs u, abs v, d)
 
(* Here is a proof, by construction, of the proposition
‘The gcd of 12 and 8 is 4’. *)
prfn
gcd_12_8 () :<prf>
GCD (12, 8, 4) =
let
prval pf = GCD_u_0 {4} ()
prval pf = GCD_u_le_v {4, 4} {4} (pf)
prval pf = GCD_u_le_v {4, 8} {4} (pf)
prval pf = GCD_u_gt_v {12, 8} {4} (pf)
in
pf
end
 
(* A lemma: the gcd is total. That is, it is defined for all
integers. *)
extern prfun
gcd_istot :
{u, v : int}
() -<prf>
[d : int]
GCD (u, v, d)
 
(* Another lemma: the gcd is a function: it has a unique value for
any given pair of arguments. *)
extern prfun
gcd_isfun :
{u, v : int}
{d, e : int}
(GCD (u, v, d),
GCD (u, v, e)) -<prf>
[d == e] void
 
(* Proof of gcd_istot. This source file will not pass typechecking
unless the proof is valid. *)
primplement
gcd_istot {u, v} () =
let
prfun
gcd_istot__nat_nat__ {u, v : nat | u != 0 || v != 0} .<u + v>.
() :<prf> [d : pos] GCD (u, v, d) =
sif v == 0 then
GCD_u_0 ()
else sif u == 0 then
GCD_0_v ()
else sif u <= v then
GCD_u_le_v (gcd_istot__nat_nat__ {u, v - u} ())
else
GCD_u_gt_v (gcd_istot__nat_nat__ {u - v, v} ())
 
prfun
gcd_istot__int_int__ {u, v : int | u != 0 || v != 0} .<>.
() :<prf> [d : pos] GCD (u, v, d) =
sif u < 0 || v < 0 then
GCD_u_or_v_neg (gcd_istot__nat_nat__ {abs u, abs v} ())
else
gcd_istot__nat_nat__ {u, v} ()
in
sif u == 0 && v == 0 then
GCD_0_0 ()
else
gcd_istot__int_int__ {u, v} ()
end
 
(* Proof of gcd_isfun. This source file will not pass typechecking
unless the proof is valid. *)
primplement
gcd_isfun {u, v} {d, e} (pfd, pfe) =
let
prfun
gcd_isfun__nat_nat__ {u, v : nat}
{d, e : int}
.<u + v>.
(pfd : GCD (u, v, d),
pfe : GCD (u, v, e)) :<prf> [d == e] void =
case+ pfd of
| GCD_0_0 () =>
{
prval GCD_0_0 () = pfe
}
| GCD_u_0 () =>
{
prval GCD_u_0 () = pfe
}
| GCD_0_v () =>
{
prval GCD_0_v () = pfe
}
| GCD_u_le_v pfd1 =>
{
prval GCD_u_le_v pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
| GCD_u_gt_v pfd1 =>
{
prval GCD_u_gt_v pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
in
sif u < 0 || v < 0 then
{
prval GCD_u_or_v_neg pfd1 = pfd
prval GCD_u_or_v_neg pfe1 = pfe
prval _ = gcd_isfun__nat_nat__ (pfd1, pfe1)
}
else
gcd_isfun__nat_nat__ (pfd, pfe)
end</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">GCD(a,b) {
Return b=0 ? Abs(a) : Gcd(b,mod(a,b))
}</langsyntaxhighlight>
Significantly faster than recursion:
<langsyntaxhighlight AutoHotkeylang="autohotkey">GCD(a, b) {
while b
b := Mod(a | 0x0, a := b)
return a
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
_GCD(18, 12)
_GCD(1071, 1029)
Line 957 ⟶ 1,556:
WEnd
EndFunc ;==>_GCD
</syntaxhighlight>
</lang>
 
Output: <pre>GCD of 18 : 12 = 6
Line 965 ⟶ 1,564:
=={{header|AWK}}==
The following scriptlet defines the gcd() function, then reads pairs of numbers from stdin, and reports their gcd on stdout.
<langsyntaxhighlight lang="awk">$ awk 'function gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}'
12 16
4
Line 971 ⟶ 1,570:
11
45 67
1</langsyntaxhighlight>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">Lbl GCD
r₁→A
r₂→B
Line 981 ⟶ 1,580:
Return
End
GCD(B,A^B)</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="applesoftbasic">0 A = ABS(INT(A))
===Iterative===
1 B = ABS(INT(B))
<lang qbasic>function gcd(a%, b%)
2 GCD = ifA a* >NOT bNOT thenB
3 FOR B = B + A * NOT B TO 0 STEP 0
factor = a
4 else A = GCD
5 factorGCD = bB
6 B = A - INT (A / GCD) * GCD
end if
7 NEXT B</syntaxhighlight>
for l = factor to 1 step -1
if a mod l = 0 and b mod l = 0 then
gcd = l
end if
next l
gcd = 1
end function</lang>
===Recursive===
<lang qbasic>function gcd(a%, b%)
if a = 0 gcd = b
if b = 0 gcd = a
if a > b gcd = gcd(b, a mod b)
gcd = gcd(a, b mod a)
end function</lang>
 
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 DEF GCD(A,B)
110 DO WHILE B>0
120 LET T=B
130 LET B=MOD(A,B)
140 LET A=T
150 LOOP
160 LET GCD=A
170 END DEF
180 PRINT GCD(12,16)</lang>
 
==={{header|Sinclair ZX81 BASIC}}===
<lang basic> 10 LET M=119
20 LET N=544
30 LET R=M-N*INT (M/N)
40 IF R=0 THEN GOTO 80
50 LET M=N
60 LET N=R
70 GOTO 30
80 PRINT N</lang>
{{out}}
<pre>17</pre>
 
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
===Solución iterativa=Iterative====
<langsyntaxhighlight lang="freebasic">
function gcdI(x, y)
while y
Line 1,051 ⟶ 1,613:
print : print "GCD(";a;", ";b;") = "; gcdI(a, b)
print : print "GCD(";a;", 111) = "; gcdI(a, 111)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,057 ⟶ 1,619:
</pre>
 
===Solución recursiva=Recursive====
<langsyntaxhighlight lang="freebasic">
function gcdp(a, b)
if b = 0 then return a
Line 1,067 ⟶ 1,629:
return gcdp(abs(a), abs(b))
end function
</syntaxhighlight>
</lang>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> DEF FN_GCD_Iterative_Euclid(A%, B%)
LOCAL C%
WHILE B%
C% = A%
A% = B%
B% = C% MOD B%
ENDWHILE
= ABS(A%)</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|BASIC256}}
====Iterative====
<syntaxhighlight lang="qbasic">100 cls
110 a = 40902
120 b = 24140
130 print : print "GCD(";a;", ";b;") = ";gcdi(a,b)
140 print : print "GCD(";a;", 111) = ";gcdi(a,111)
170 end
 
190 sub gcdi(x,y)
200 while y
210 t = y
220 y = x mod y
230 x = t
240 wend
250 gcdi = x
260 end sub</syntaxhighlight>
 
==={{header|FreeBASIC}}===
====Iterative solution====
<syntaxhighlight lang="freebasic">' version 17-06-2015
' compile with: fbc -s console
 
Function gcd(x As ULongInt, y As ULongInt) As ULongInt
Dim As ULongInt t
While y
t = y
y = x Mod y
x = t
Wend
Return x
End Function
 
' ------=< MAIN >=------
 
Dim As ULongInt a = 111111111111111
Dim As ULongInt b = 11111
 
Print : Print "GCD(";a;", ";b;") = "; gcd(a, b)
Print : Print "GCD(";a;", 111) = "; gcd(a, 111)
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>GCD(111111111111111, 11111) = 11111
GCD(111111111111111, 111) = 111</pre>
 
====Recursive solution====
<syntaxhighlight lang="freebasic">function gcdp( a as uinteger, b as uinteger ) as uinteger
if b = 0 then return a
return gcdp( b, a mod b )
end function
 
function gcd(a as integer, b as integer) as uinteger
return gcdp( abs(a), abs(b) )
end function</syntaxhighlight>
 
==={{header|GFA Basic}}===
<syntaxhighlight lang="basic">
'
' Greatest Common Divisor
'
a%=24
b%=112
PRINT "GCD of ";a%;" and ";b%;" is ";@gcd(a%,b%)
'
' Function computes gcd
'
FUNCTION gcd(a%,b%)
LOCAL t%
'
WHILE b%<>0
t%=a%
a%=b%
b%=t% MOD b%
WEND
'
RETURN ABS(a%)
ENDFUNC
</syntaxhighlight>
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="gwbasic">10 INPUT A, B
20 IF A < 0 THEN A = -A
30 IF B < 0 THEN B = -B
40 GOTO 70
50 PRINT A
60 END
70 IF B = 0 THEN GOTO 50
80 TEMP = B
90 B = A MOD TEMP
100 A = TEMP
110 GOTO 70</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 DEF GCD(A,B)
110 DO WHILE B>0
120 LET T=B
130 LET B=MOD(A,B)
140 LET A=T
150 LOOP
160 LET GCD=A
170 END DEF
180 PRINT GCD(12,16)</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">'iterative Euclid algorithm
print GCD(-2,16)
end
 
function GCD(a,b)
while b
c = a
a = b
b = c mod b
wend
GCD = abs(a)
end function
</syntaxhighlight>
 
==={{header|PureBasic}}===
====Iterative====
<syntaxhighlight lang="purebasic">
Import "" ;msvcrt.lib
AbsI(Quad.q) As "_abs64"
AbsL(Long.l) As "labs"
EndImport
Procedure.i GCD(u.i, v.i)
Protected.i t
While v <> 0
t = v
v = u % v
u = t
Wend
ProcedureReturn AbsI(u) ; Avoid float conversion with Abs(u).
EndProcedure
Debug GCD(18, 12) ; 6
Debug GCD(1071, 1029) ; 21
Debug GCD(3528, -3780) ; 252
</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QuickBASIC|4.5}}
====Iterative====
<syntaxhighlight lang="qbasic">DECLARE FUNCTION gcd (a%, b%)
PRINT gcd(18, 30)
END
 
FUNCTION gcd (a%, b%)
WHILE b% <> 0
t% = b%
b% = a% MOD b%
a% = t%
WEND
gcd = ABS(a%)
END FUNCTION</syntaxhighlight>
{{out}}
<pre>
6
</pre>
 
====Recursive====
<syntaxhighlight lang="qbasic">DECLARE FUNCTION gcd (a%, b%)
PRINT gcd(30, 18)
END
 
FUNCTION gcd (a%, b%)
IF b% = 0 THEN
gcd = ABS(a%)
ELSE
gcd = gcd(b%, a% MOD b%)
END IF
END FUNCTION</syntaxhighlight>
{{out}}
<pre>
6
</pre>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">print abs(gcd(-220,160))
function gcd(gcd,b)
while b
c = gcd
gcd = b
b = c mod b
wend
end function </syntaxhighlight>
 
==={{header|S-BASIC}}===
<syntaxhighlight lang="basic">
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
 
rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
var r, temp = integer
if x < y then
begin
temp = x
x = y
y = temp
end
r = mod(x, y)
while r <> 0 do
begin
x = y
y = r
r = mod(x, y)
end
end = y
 
rem - exercise the function
 
print "The GCD of 21 and 35 is"; gcd(21,35)
print "The GCD of 23 and 35 is"; gcd(23,35)
print "The GCD of 1071 and 1029 is"; gcd(1071, 1029)
print "The GCD of 3528 and 3780 is"; gcd(3528,3780)
 
end
</syntaxhighlight>
{{out}}
<pre>The GCD of 21 and 35 is 7
The GCD of 23 and 35 is 1
The GCD of 1071 and 1029 is 21
The GCD of 3528 and 3780 is 252
</pre>
 
==={{header|Sinclair ZX81 BASIC}}===
<syntaxhighlight lang="basic"> 10 LET M=119
20 LET N=544
30 LET R=M-N*INT (M/N)
40 IF R=0 THEN GOTO 80
50 LET M=N
60 LET N=R
70 GOTO 30
80 PRINT N</syntaxhighlight>
{{out}}
<pre>17</pre>
 
==={{header|TI-83 BASIC}}, {{header|TI-89 BASIC}}===
gcd(A,B)
The ) can be omitted in TI-83 basic
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 PRINT "First number"
20 INPUT A
30 PRINT "Second number"
40 INPUT B
50 IF A<0 THEN LET A=-A
60 IF B<0 THEN LET B=-B
70 IF A>B THEN GOTO 130
80 LET B = B - A
90 IF A=0 THEN GOTO 110
100 GOTO 50
110 PRINT B
120 END
130 LET C=A
140 LET A=B
150 LET B=C
160 GOTO 70</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic">
REM Iterative solution
FUNCTION gcdI(x, y)
DO WHILE y > 0
LET t = y
LET y = remainder(x, y)
LET x = t
LOOP
LET gcdI = x
END FUNCTION
 
LET a = 111111111111111
LET b = 11111
PRINT
PRINT "GCD(";a;", ";b;") = "; gcdI(a, b)
PRINT
PRINT "GCD(";a;", 111) = "; gcdI(a, 111)
END
</syntaxhighlight>
 
==={{header|uBasic/4tH}}===
{{trans|BBC BASIC}}
<syntaxhighlight lang="text">Print "GCD of 18 : 12 = "; FUNC(_GCD_Iterative_Euclid(18,12))
Print "GCD of 1071 : 1029 = "; FUNC(_GCD_Iterative_Euclid(1071,1029))
Print "GCD of 3528 : 3780 = "; FUNC(_GCD_Iterative_Euclid(3528,3780))
 
End
 
_GCD_Iterative_Euclid Param(2)
Local (1)
Do While b@
c@ = a@
a@ = b@
b@ = c@ % b@
Loop
Return (Abs(a@))</syntaxhighlight>
{{out}}
<pre>GCD of 18 : 12 = 6
GCD of 1071 : 1029 = 21
GCD of 3528 : 3780 = 252
 
0 OK, 0:205</pre>
 
==={{header|VBA}}===
<syntaxhighlight lang="vb">Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function</syntaxhighlight>
This function uses repeated subtractions. Simple but not very efficient.
<syntaxhighlight lang="vba">Public Function GCD(a As Long, b As Long) As Long
While a <> b
If a > b Then a = a - b Else b = b - a
Wend
GCD = a
End Function</syntaxhighlight>{{out}}
Example:
<pre>print GCD(1280, 240)
80
print GCD(3475689, 23566319)
7
a=123456789
b=234736437
print GCD((a),(b))
3 </pre>
 
A note on the last example: using brackets forces a and b to be evaluated before GCD is called. Not doing this will cause a compile error because a and b are not the same type as in the function declaration (they are Variant, not Long). Alternatively you can use the conversion function CLng as in print GCD(CLng(a),CLng(b))
 
==={{header|VBScript}}===
<syntaxhighlight lang="vbscript">Function GCD(a,b)
Do
If a Mod b > 0 Then
c = a Mod b
a = b
b = c
Else
GCD = b
Exit Do
End If
Loop
End Function
 
WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,23566319) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(123456789,234736437) & "."</syntaxhighlight>
 
{{Output}}
<pre>The GCD of 48 and 18 is 6.
The GCD of 1280 and 240 is 80.
The GCD of 1280 and 240 is 7.
The GCD of 1280 and 240 is 3.</pre>
 
==={{header|Visual Basic}}===
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<syntaxhighlight lang="vb">Function GCD(ByVal a As Long, ByVal b As Long) As Long
Dim h As Long
 
If a Then
If b Then
Do
h = a Mod b
a = b
b = h
Loop While b
End If
GCD = Abs(a)
Else
GCD = Abs(b)
End If
End Function
 
Sub Main()
' testing the above function
 
Debug.Assert GCD(12, 18) = 6
Debug.Assert GCD(1280, 240) = 80
Debug.Assert GCD(240, 1280) = 80
Debug.Assert GCD(-240, 1280) = 80
Debug.Assert GCD(240, -1280) = 80
Debug.Assert GCD(0, 0) = 0
Debug.Assert GCD(0, 1) = 1
Debug.Assert GCD(1, 0) = 1
Debug.Assert GCD(3475689, 23566319) = 7
Debug.Assert GCD(123456789, 234736437) = 3
Debug.Assert GCD(3780, 3528) = 252
End Sub</syntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Greatest common divisor
PROGRAM "gcddemo"
VERSION "0.001"
 
DECLARE FUNCTION Entry()
DECLARE FUNCTION GcdRecursive(u&, v&)
DECLARE FUNCTION GcdIterative(u&, v&)
DECLARE FUNCTION GcdBinary(u&, v&)
 
FUNCTION Entry()
m& = 49865
n& = 69811
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdIterative(m&, n&); " (iterative)"
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdRecursive(m&, n&); " (recursive)"
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdBinary (m&, n&); " (binary)"
END FUNCTION
 
FUNCTION GcdRecursive(u&, v&)
IF u& MOD v& <> 0 THEN
RETURN GcdRecursive(v&, u& MOD v&)
ELSE
RETURN v&
END IF
END FUNCTION
 
FUNCTION GcdIterative(u&, v&)
DO WHILE v& <> 0
t& = u&
u& = v&
v& = t& MOD v&
LOOP
RETURN ABS(u&)
END FUNCTION
 
FUNCTION GcdBinary(u&, v&)
u& = ABS(u&)
v& = ABS(v&)
IF u& < v& THEN
t& = u&
u& = v&
v& = t&
END IF
IF v& = 0 THEN
RETURN u&
ELSE
k& = 1
DO WHILE (u& MOD 2 = 0) && (v& MOD 2 = 0)
u& = u& >> 1
v& = v& >> 1
k& = k& << 1
LOOP
IF u& MOD 2 = 0 THEN
t& = u&
ELSE
t& = -v&
END IF
DO WHILE t& <> 0
DO WHILE t& MOD 2 = 0
t& = t& \ 2
LOOP
IF t& > 0 THEN
u& = t&
ELSE
v& = -t&
END IF
t& = u& - v&
LOOP
RETURN u& * k&
END IF
END FUNCTION
 
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
GCD(49865, 69811): 9973 (iterative)
GCD(49865, 69811): 9973 (recursive)
GCD(49865, 69811): 9973 (binary)
</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub gcd(u, v)
local t
u = int(abs(u))
v = int(abs(v))
while(v)
t = u
u = v
v = mod(t, v)
wend
return u
end sub
 
print "Greatest common divisor: ", gcd(12345, 9876)</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 FOR n=1 TO 3
20 READ a,b
30 PRINT "GCD of ";a;" and ";b;" = ";
40 GO SUB 70
50 NEXT n
60 STOP
70 IF b=0 THEN PRINT ABS (a): RETURN
80 LET c=a: LET a=b: LET b=FN m(c,b): GO TO 70
90 DEF FN m(a,b)=a-INT (a/b)*b
100 DATA 12,16,22,33,45,67</syntaxhighlight>
 
=={{header|Batch File}}==
Recursive method
<langsyntaxhighlight lang="dos">:: gcd.cmd
@echo off
:gcd
Line 1,093 ⟶ 2,183:
echo Syntax:
echo GCD {a} {b}
echo.</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<lang bbcbasic> DEF FN_GCD_Iterative_Euclid(A%, B%)
LOCAL C%
WHILE B%
C% = A%
A% = B%
B% = C% MOD B%
ENDWHILE
= ABS(A%)</lang>
 
=={{header|Bc}}==
Line 1,110 ⟶ 2,190:
 
Utility functions:
<langsyntaxhighlight lang="bc">define even(a)
{
if ( a % 2 == 0 ) {
Line 1,126 ⟶ 2,206:
return(a);
}
}</langsyntaxhighlight>
 
'''Iterative (Euclid)'''
<langsyntaxhighlight lang="bc">define gcd_iter(u, v)
{
while(v) {
Line 1,137 ⟶ 2,217:
}
return(abs(u));
}</langsyntaxhighlight>
 
'''Recursive'''
 
<langsyntaxhighlight lang="bc">define gcd(u, v)
{
if (v) {
Line 1,148 ⟶ 2,228:
return (abs(u));
}
}</langsyntaxhighlight>
 
'''Iterative (Binary)'''
 
<langsyntaxhighlight lang="bc">define gcd_bin(u, v)
{
u = abs(u);
Line 1,183 ⟶ 2,263:
}
return (u * k);
}</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let gcd(m,n) = n=0 -> m, gcd(n, m rem n)
Line 1,197 ⟶ 2,277:
show(1071,1029)
show(3528,3780)
$)</langsyntaxhighlight>
{{out}}
<pre>gcd(18, 12) = 6
Line 1,204 ⟶ 2,284:
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">#v&< @.$<
:<\g05%p05:_^#</langsyntaxhighlight>
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">Gcd ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}</langsyntaxhighlight>
 
Example:
<syntaxhighlight lang ="bqn">21 Gcd 35</langsyntaxhighlight>
<pre>7</pre>
 
=={{header|Bracmat}}==
Bracmat uses the Euclidean algorithm to simplify fractions. The <code>den</code> function extracts the denominator from a fraction.
<langsyntaxhighlight lang="bracmat">(gcd=a b.!arg:(?a.?b)&!b*den$(!a*!b^-1)^-1);</langsyntaxhighlight>
Example:
<pre>{?} gcd$(49865.69811)
{!} 9973</pre>
 
=={{header|Bruijn}}==
As defined in <code>std/Math</code>.
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/Number .
 
gcd y [[[=?0 1 (2 0 (1 % 0))]]]
 
:test ((gcd (+2) (+4)) =? (+2)) ([[1]])
:test ((gcd (+10) (+5)) =? (+5)) ([[1]])
:test ((gcd (+3) (+8)) =? (+1)) ([[1]])
</syntaxhighlight>
 
=={{header|C}}==
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="c">int
gcd_iter(int u, int v) {
if (u < 0) u = -u;
Line 1,229 ⟶ 2,322:
if (v) while ((u %= v) && (v %= u));
return (u + v);
}</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="c">int gcd(int u, int v) {
return (v != 0)?gcd(v, u%v):u;
}</langsyntaxhighlight>
 
===Iterative binary algorithm===
<syntaxhighlight lang="c">int gcd_bin(int u, int v) {
<lang c>int
gcd_bin(int u, int v) {
int t, k;
 
Line 1,252 ⟶ 2,344:
 
k = 1;
while ((u & 1) == 0 && (v & 1) == 0) { /* u, v - even */
u >>= 1; v >>= 1;
k <<= 1;
Line 1,259 ⟶ 2,351:
t = (u & 1) ? -v : u;
while (t) {
while ((t & 1) == 0)
t >>= 1;
 
Line 1,270 ⟶ 2,362:
}
return u * k;
}</langsyntaxhighlight>
 
=={{header|c sharp|C#}}==
===Iterative===
<langsyntaxhighlight lang="csharp">
static void Main()
{
Line 1,300 ⟶ 2,392:
return a;
}
</syntaxhighlight>
</lang>
 
Example output:
Line 1,322 ⟶ 2,414:
</pre>
===Recursive===
<langsyntaxhighlight lang="csharp">
static void Main(string[] args)
{
Line 1,346 ⟶ 2,438:
return b==0 ? a : gcd(b, a % b);
}
</syntaxhighlight>
</lang>
 
Example output:
Line 1,369 ⟶ 2,461:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
 
int main() {
std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n";
}</langsyntaxhighlight>
 
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <boost/math/common_factor.hpp>
#include <iostream>
 
int main() {
std::cout << "The greatest common divisor of 12 and 18 is " << boost::math::gcd(12, 18) << "!\n";
}</langsyntaxhighlight>
 
{{out}}
Line 1,391 ⟶ 2,483:
===Euclid's Algorithm===
 
<langsyntaxhighlight lang="lisp">(defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
[a b]
(if (zero? b)
a
(recur b (mod a b))))</langsyntaxhighlight>
 
That <code>recur</code> call is the same as <code>(gcd b (mod a b))</code>, but makes use of Clojure's explicit tail call optimization.
Line 1,402 ⟶ 2,494:
This can be easily extended to work with variadic arguments:
 
<langsyntaxhighlight lang="lisp">(defn gcd*
"greatest common divisor of a list of numbers"
[& lst]
(reduce gcd
lst))</langsyntaxhighlight>
 
=== Stein's Algorithm (Binary GCD) ===
 
<langsyntaxhighlight lang="lisp">(defn stein-gcd [a b]
(cond
(zero? a) b
Line 1,417 ⟶ 2,509:
(and (even? a) (odd? b)) (recur (unsigned-bit-shift-right a 1) b)
(and (odd? a) (even? b)) (recur a (unsigned-bit-shift-right b 1))
(and (odd? a) (odd? b)) (recur (unsigned-bit-shift-right (Math/abs (- a b)) 1) (min a b))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">gcd = proc (a, b: int) returns (int)
while b~=0 do
a, b := b, a//b
Line 1,436 ⟶ 2,528:
|| int$unparse(gcd(as[i], bs[i])))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>gcd(18, 12) = 6
Line 1,443 ⟶ 2,535:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. GCD.
 
Line 1,470 ⟶ 2,562:
END-PERFORM
DISPLAY "The gcd is " A
STOP RUN.</langsyntaxhighlight>
 
=={{header|Cobra}}==
 
<langsyntaxhighlight lang="cobra">
class Rosetta
def gcd(u as number, v as number) as number
Line 1,487 ⟶ 2,579:
print "gcd of [96] and [27] is [.gcd(27, 96)]"
print "gcd of [51] and [34] is [.gcd(34, 51)]"
</syntaxhighlight>
</lang>
 
Output:
Line 1,500 ⟶ 2,592:
 
Simple recursion
<langsyntaxhighlight lang="coffeescript">
gcd = (x, y) ->
if y == 0 then x else gcd y, x % y
</syntaxhighlight>
</lang>
 
Since JS has no TCO, here's a version with no recursion
<langsyntaxhighlight lang="coffeescript">
gcd = (x, y) ->
[1..(Math.min x, y)].reduce (acc, v) ->
if x % v == 0 and y % v == 0 then v else acc
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Common Lisp provides a ''gcd'' function.
 
<langsyntaxhighlight lang="lisp">CL-USER> (gcd 2345 5432)
7</langsyntaxhighlight>
 
Here is an implementation using the do macro. We call the function <code>gcd*</code> so as not to conflict with <code>common-lisp:gcd</code>.
 
<langsyntaxhighlight lang="lisp">(defun gcd* (a b)
(do () ((zerop b) (abs a))
(shiftf a b (mod a b))))</langsyntaxhighlight>
 
Here is a tail-recursive implementation.
 
<langsyntaxhighlight lang="lisp">(defun gcd* (a b)
(if (zerop b)
a
(gcd2 b (mod a b))))</langsyntaxhighlight>
 
The last implementation is based on the loop macro.
 
<langsyntaxhighlight lang="lisp">(defun gcd* (a b)
(loop for x = a then y
and y = b then (mod x y)
until (zerop y)
finally (return x)))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Operations;
IMPORT StdLog,Args,Strings;
Line 1,570 ⟶ 2,662:
 
END Operations.
</syntaxhighlight>
</lang>
Execute:<br/>
^Q Operations.DoGcd 12 8 ~<br/>
Line 1,585 ⟶ 2,677:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.numeric;
 
long myGCD(in long x, in long y) pure nothrow @nogc {
Line 1,596 ⟶ 2,688:
gcd(15, 10).writeln; // From Phobos.
myGCD(15, 10).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>5
Line 1,602 ⟶ 2,694:
 
=={{header|Dc}}==
<syntaxhighlight lang ="dc">[dSa%Lard0<G]dsGx+</langsyntaxhighlight>
This code assumes that there are two integers on the stack.
<pre>dc -e'28 24 [dSa%Lard0<G]dsGx+ p'</pre>
Line 1,610 ⟶ 2,702:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec gcd(word m, n) word:
word t;
while n ~= 0 do
Line 1,628 ⟶ 2,720:
show(1071, 1029);
show(3528, 3780)
corp</langsyntaxhighlight>
{{out}}
<pre>gcd(18, 12) = 6
gcd(1071, 1029) = 21
gcd(3528, 3780) = 252</pre>
 
=={{header|dt}}==
{{works with|dt|1.3.1}}
<syntaxhighlight lang="dt">[[a b]: a [b a b % gcd] b do?] \gcd def</syntaxhighlight>
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">PrintLn(Gcd(231, 210));</langsyntaxhighlight>
Output:
<pre>21</pre>
Line 1,643 ⟶ 2,739:
{{trans|Go}}
 
<langsyntaxhighlight lang="dyalect">func gcd(a, b) {
func bgcd(a, b, res) {
if a == b {
Line 1,661 ⟶ 2,757:
return bgcd(a, b, 1)
}
 
var testdata = [
(a =: 33, b =: 77),
(a =: 49865, b =: 69811)
]
 
for v in testdata {
print("gcd(\(v:.a), \(v:.b)) = \(gcd(v:.a, v:.b))")
}</langsyntaxhighlight>
 
{{out}}
Line 1,679 ⟶ 2,775:
{{trans|Python}}
 
<langsyntaxhighlight lang="e">def gcd(var u :int, var v :int) {
while (v != 0) {
def r := u %% v
Line 1,686 ⟶ 2,782:
}
return u.abs()
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight>
<lang>func gcd a b . res .
func gcd whilea b <> 0.
while hb =<> b0
b = aswap moda b
a b = hb mod a
.
res =return a
.
callprint gcd 120 35 r
</syntaxhighlight>
print r</lang>
 
=={{header|EDSAC order code}}==
The EDSAC had no division instruction,
so the GCD routine below has to include its own code for division.
<langsyntaxhighlight lang="edsac">
[Greatest common divisor for Rosetta Code.
Program for EDSAC, Initial Orders 2.]
Line 1,856 ⟶ 2,952:
E 14 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,868 ⟶ 2,964:
{{trans|D}}
 
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,896 ⟶ 2,992:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<langsyntaxhighlight lang="elena">import system'math;
import extensions;
Line 1,934 ⟶ 3,030:
printGCD(36,19);
printGCD(36,33);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,949 ⟶ 3,045:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def gcd(a,0), do: abs(a)
def gcd(a,b), do: gcd(b, rem(a,b))
Line 1,955 ⟶ 3,051:
 
IO.puts RC.gcd(1071, 1029)
IO.puts RC.gcd(3528, 3780)</langsyntaxhighlight>
 
{{out}}
Line 1,963 ⟶ 3,059:
</pre>
 
=={{header|Emacs LispElm}}==
<syntaxhighlight lang="elm">import Html exposing (Html, div, h1, p, text)
import Html.Attributes exposing (style)
 
 
<lang lisp>(defun gcd (a b)
-- Test cases
 
nr1 : Int
nr1 =
2 * 3 * 5 * 7 * 11
 
 
nr2 : Int
nr2 =
7 * 11 * 13 * 17 * 23
 
 
main : Html msg
main =
div [ style "margin" "5%", style "font-size" "1.5em", style "color" "blue" ]
[ h1 [ style "font-size" "1.5em" ] [ text "GCD Calculator" ]
, text
("number a = "
++ String.fromInt nr1
++ ", number b = "
++ String.fromInt nr2
)
, p [] [ text ("GCD = " ++ String.fromInt (gcd nr1 nr2)) ]
]
 
 
gcd : Int -> Int -> Int
gcd anr bnr =
if bnr /= 0 then
gcd bnr (modBy bnr anr)
 
else
abs anr
</syntaxhighlight>
{{out}}
<pre>
number a = 2310, number b = 391391
GCD = 77
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun gcd (a b)
(cond
((< a b) (gcd a (- b a)))
((> a b) (gcd (- a b) b))
(t a)))</langsyntaxhighlight>
 
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(gcd).
-export([main/0]).
Line 1,981 ⟶ 3,121:
gcd(A, 0) -> A;
 
gcd(A, B) -> gcd(B, A rem B).</langsyntaxhighlight>
{{out}}
<pre>4
Line 1,988 ⟶ 3,128:
=={{header|ERRE}}==
This is a iterative version.
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM EUCLIDE
! calculate G.C.D. between two integer numbers
Line 2,010 ⟶ 3,150:
PRINT("G.C.D. between";J%;"and";K%;"is";MCD%)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
Input two numbers : ? 112,44
G.C.D. between 112 and 44 is 4
 
=={{header|Euler}}==
The original Euler didn't have built-in loops, this defines a while-loop procedure, as in the [[Steady Squares#Euler]] sample.
<br>
'''begin'''
'''new''' while; '''new''' gcd;
while <- ` '''formal''' condition; '''formal''' loopBody;
'''begin'''
'''label''' again;
again: '''if''' condition '''then''' '''begin''' loopBody; '''goto''' again '''end''' '''else''' 0
'''end'''
'
;
gcd <- ` '''formal''' m; '''formal''' n;
'''begin'''
'''new''' a; '''new''' b; '''new''' newA;
a <- '''abs''' m;
b <- '''abs''' n;
while( ` b <> 0 '
, ` '''begin'''
newA <- b;
b <- a '''mod''' b;
a <- newA
'''end'''
'
);
a
'''end'''
'
;
'''out''' gcd( -21, 35 )
'''end''' $
 
=={{header|Euler Math Toolbox}}==
Line 2,019 ⟶ 3,194:
Non-recursive version in Euler Math Toolbox. Note, that there is a built-in command.
 
<syntaxhighlight lang="text">
>ggt(123456795,1234567851)
33
Line 2,033 ⟶ 3,208:
>myggt(123456795,1234567851)
33
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{trans|C/C++}}
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="euphoria">function gcd_iter(integer u, integer v)
integer t
while v do
Line 2,050 ⟶ 3,225:
return u
end if
end function</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="euphoria">function gcd(integer u, integer v)
if v then
return gcd(v, remainder(u, v))
Line 2,061 ⟶ 3,236:
return u
end if
end function</langsyntaxhighlight>
 
===Iterative binary algorithm===
<langsyntaxhighlight lang="euphoria">function gcd_bin(integer u, integer v)
integer t, k
if u < 0 then -- abs(u)
Line 2,103 ⟶ 3,278:
end while
return u * k
end function</langsyntaxhighlight>
 
=={{header|Excel}}==
Excel's GCD can handle multiple values. Type in a cell:
<langsyntaxhighlight lang="excel">=GCD(A1:E1)</langsyntaxhighlight>
{{Out|Sample Output}}
This will get the GCD of the first 5 cells of the first row.
Line 2,114 ⟶ 3,289:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
## இந்த நிரல் இரு எண்களுக்கு இடையிலான மீச்சிறு பொது மடங்கு (LCM), மீப்பெரு பொது வகுத்தி (GCD) என்ன என்று கணக்கிடும்
 
Line 2,175 ⟶ 3,350:
 
பதிப்பி "நீங்கள் தந்த இரு எண்களின் மீபொவ (மீப்பெரு பொது வகுத்தி, GCD) = ", மீபொவ(அ, ஆ)
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let rec gcd a b =
if b = 0
Line 2,185 ⟶ 3,360:
>gcd 400 600
val it : int = 200</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: gcd ( a b -- c )
[ abs ] [
[ nip ] [ mod ] 2bi gcd
] if-zero ;</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">10 15$ [0=~][$@$@$@\/*-$]#%. { gcd(10,15)=5 }</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 2,219 ⟶ 3,394:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fermat}}==
<syntaxhighlight lang ="fermat">GCD(a,b)</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: gcd ( a b -- n )
begin dup while tuck mod repeat drop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="fortran">recursive function gcd_rec(u, v) result(gcd)
integer :: gcd
integer, intent(in) :: u, v
Line 2,240 ⟶ 3,415:
gcd = v
end if
end function gcd_rec</langsyntaxhighlight>
 
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="fortran">subroutine gcd_iter(value, u, v)
integer, intent(out) :: value
integer, intent(inout) :: u, v
Line 2,254 ⟶ 3,429:
enddo
value = abs(u)
end subroutine gcd_iter</langsyntaxhighlight>
 
A different version, and implemented as function
 
<langsyntaxhighlight lang="fortran">function gcd(v, t)
integer :: gcd
integer, intent(in) :: v, t
Line 2,272 ⟶ 3,447:
end do
gcd = b ! abs(b)
end function gcd</langsyntaxhighlight>
 
===Iterative binary algorithm===
<langsyntaxhighlight lang="fortran">subroutine gcd_bin(value, u, v)
integer, intent(out) :: value
integer, intent(inout) :: u, v
Line 2,314 ⟶ 3,489:
enddo
value = u * k
end subroutine gcd_bin</langsyntaxhighlight>
 
===Notes on performance===
Line 2,321 ⟶ 3,496:
<tt>gcd_bin(40902, 24140)</tt> takes us about '''2.5''' µsec
 
===Iterative binary algorithm in Fortran 2008===
=={{header|Free Pascal}}==
{{works with|Fortran|2008}}
See [[#Pascal / Delphi / Free Pascal]].
{{works with|Fortran|2018}}
{{trans|ATS}}
Fortran 2008 introduces new intrinsic functions for integer operations that nowadays usually have hardware support, such as TRAILZ to count trailing zeros.
<syntaxhighlight lang="fortran">! Stein’s algorithm implemented in Fortran 2008.
! Translated from my implementation for ATS/Postiats.
 
elemental function gcd (u, v) result (d)
=={{header|FreeBASIC}}==
implicit none
===Iterative solution===
integer, intent(in) :: u, v
<lang FreeBASIC>' version 17-06-2015
integer :: d
' compile with: fbc -s console
 
integer :: x, y
Function gcd(x As ULongInt, y As ULongInt) As ULongInt
 
! gcd(x,y) = gcd(u,v), but x and y are non-negative and x <= y.
Dim As ULongInt t
x = min (abs (u), abs (v))
y = max (abs (u), abs (v))
 
if (x While== y0) then
td = y
else
y = x Mod y
d = gcd_pos_pos (x, = ty)
end Wendif
 
contains
Return x
 
elemental function gcd_pos_pos (u, v) result (d)
End Function
integer, intent(in) :: u, v
integer :: d
 
integer :: n
' ------=< MAIN >=------
integer :: x, y
integer :: p, q
 
! n = the number of common factors of two in u and v.
Dim As ULongInt a = 111111111111111
n = trailz (ior (u, v))
Dim As ULongInt b = 11111
 
! Remove the common twos from u and v, giving x and y.
Print : Print "GCD(";a;", ";b;") = "; gcd(a, b)
Print : Print "GCD(";a;", 111)x = ";ishft gcd(au, 111-n)
y = ishft (v, -n)
 
! Make both numbers odd. One of the numbers already was odd.
! There is no effect on the value of their gcd.
x = ishft (x, -trailz (x))
y = ishft (y, -trailz (y))
 
do while (x /= y)
! If x > y then swap x and y, renaming them p
! and q. Thus p <= q, and gcd(p,q) = gcd(x,y).
p = min (x, y)
q = max (x, y)
 
x = p ! x remains odd.
q = q - p
y = ishft (q, -trailz (q)) ! Make y odd again.
end do
 
! Put the common twos back in.
d = ishft (x, n)
end function gcd_pos_pos
 
end function gcd
 
program test_gcd
implicit none
 
interface
elemental function gcd (u, v) result (d)
integer, intent(in) :: u, v
integer :: d
end function gcd
end interface
 
write (*, '("gcd (0, 0) = ", I0)') gcd (0, 0)
write (*, '("gcd (0, 10) = ", I0)') gcd (0, 10)
write (*, '("gcd (-6, -9) = ", I0)') gcd (-6, -9)
write (*, '("gcd (64 * 5, -16 * 3) = ", I0)') gcd (64 * 5, -16 * 3)
write (*, '("gcd (40902, 24140) = ", I0)') gcd (40902, 24140)
write (*, '("gcd (-40902, 24140) = ", I0)') gcd (-40902, 24140)
write (*, '("gcd (40902, -24140) = ", I0)') gcd (40902, -24140)
write (*, '("gcd (-40902, -24140) = ", I0)') gcd (-40902, -24140)
write (*, '("gcd (24140, 40902) = ", I0)') gcd (24140, 40902)
 
end program test_gcd</syntaxhighlight>
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>GCDgcd (1111111111111110, 111110) = 111110
gcd (0, 10) = 10
GCD(111111111111111, 111) = 111</pre>
gcd (-6, -9) = 3
gcd (64 * 5, -16 * 3) = 16
gcd (40902, 24140) = 34
gcd (-40902, 24140) = 34
gcd (40902, -24140) = 34
gcd (-40902, -24140) = 34
gcd (24140, 40902) = 34</pre>
 
=={{header|Free Pascal}}==
===Recursive solution===
See [[#Pascal / Delphi / Free Pascal]].
<lang freebasic>function gcdp( a as uinteger, b as uinteger ) as uinteger
if b = 0 then return a
return gcdp( b, a mod b )
end function
 
function gcd(a as integer, b as integer) as uinteger
return gcdp( abs(a), abs(b) )
end function</lang>
 
=={{header|Frege}}==
<langsyntaxhighlight lang="fsharp">module gcd.GCD where
 
pure native parseInt java.lang.Integer.parseInt :: String -> Int
Line 2,381 ⟶ 3,607:
(a:b:_) = args
println $ gcd' (parseInt a) (parseInt b)
</syntaxhighlight>
</lang>
 
=={{header|Frink}}==
Frink has a builtin <CODE>gcd[x,y]</CODE> function that returns the GCD of two integers (which can be arbitrarily large.)
<langsyntaxhighlight lang="frink">
println[gcd[12345,98765]]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
FunL has pre-defined function <code>gcd</code> in module <code>integers</code> defined as:
 
<langsyntaxhighlight lang="funl">def
gcd( 0, 0 ) = error( 'integers.gcd: gcd( 0, 0 ) is undefined' )
gcd( a, b ) =
Line 2,399 ⟶ 3,625:
_gcd( a, b ) = _gcd( b, a%b )
 
_gcd( abs(a), abs(b) )</langsyntaxhighlight>
 
 
=={{header|FutureBasic}}==
This is a nearly-trivial 6-line function, so we've dressed it up a bit to show how easily FB builds a full, interactive application. In FB, when you complete your code and hit RUN, the built app can open in as little as 3 seconds.
<lang futurebasic>
 
local fn gcd( a as long, b as long )
[[File:New_app_in_finder.png|200px|frameless]]
dim as long result
 
It also appears in the dock, where you can run it again with a single click.
 
[[File:New_app_in_Mac_dock.png|45px|frameless]]
if ( b != 0 )
result = fn gcd( b, a mod b)
else
result = abs(a)
end if
end fn = result
</lang>
 
The running app looks like this—we added a button to generate random examples to
process, and an interactive design that instantly responds to each change in an input field.
 
[[File:Running_app.png|280px|frameless]]
 
<syntaxhighlight lang="futurebasic">
begin enum 1 // Object tags
_fldA
_ansA
_fldB
_ansB
_rand
end enum
 
void local fn BuildMacInterface //15-line GUI
window 1, @"Greatest Common Divisor", ( 0, 0, 380, 130 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
textfield _fldA,,, ( 20, 89, 156, 21 )
ControlSetAlignment( _fldA, NSTextAlignmentRight )
ControlSetFormat( _fldA, @"0123456789", Yes, 18, 0 )
textfield _fldB,,, ( 20, 57, 156, 24 )
ControlSetAlignment( _fldB, NSTextAlignmentRight )
ControlSetFormat( _fldB, @"0123456789", Yes, 18, 0 )
textlabel _ansA, @"= ", ( 182, 91, 185, 16 )
textlabel _ansB, @"= ", ( 182, 62, 185, 16 )
button _rand,,,@"Random demo", ( 129, 13, 122, 32 )
menu 1,,, @"File" : menu 1,0,, @"Close", @"w" : MenuItemSetAction(1,0,@"performClose:")
editmenu 2
WindowMakeFirstResponder( 1, _fldA )
end fn
 
local fn GCD( a as long, b as long ) as long //the requested function
while b
long c = a mod b
a = b : b = c
wend
end fn = a
 
void local fn DoDialog( ev as Long, tag as long ) //This makes it interactive
long a, b, c
select ev
case _textFieldDidchange //Find GCD of edit fields' contents
a = fn ControlIntegerValue( _fldA )
b = fn ControlIntegerValue( _fldB )
if a + b == 0 then textlabel _ansA, @"= 0" : textlabel _ansB, @"= 0" : exit fn
c = fn GCD( a, b )
textlabel _ansA, fn stringwithformat(@"= %ld x %ld", c, a / c )
textlabel _ansB, fn stringwithformat(@"= %ld x %ld", c, b / c )
case _btnclick //Fill edit fields with random content, then process
select tag
case _rand
c = rnd(65536)
textfield _fldA,,str( c * rnd(65536) )
textfield _fldB,,str( c * rnd(65536) )
fn DoDialog( _textFieldDidchange, 0 )
end select
case _windowWillClose : end
end select
end fn
 
fn BuildMacInterface
on dialog fn doDialog
handleevents
</syntaxhighlight>
{{output}}
[[File:Screenshot 2023-07-30 at 1.01.00 AM.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
GcdInt(35, 42);
# 7
Line 2,435 ⟶ 3,721:
 
GcdInteger(35, 42);
# 7</langsyntaxhighlight>
 
=={{header|Genyris}}==
===Recursive===
<langsyntaxhighlight lang="genyris">def gcd (u v)
u = (abs u)
v = (abs v)
cond
(equal? v 0) u
else (gcd v (% u v))</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="genyris">def gcd (u v)
u = (abs u)
v = (abs v)
Line 2,454 ⟶ 3,740:
u = v
v = tmp
u</langsyntaxhighlight>
 
=={{header|GFA Basic}}==
 
<lang basic>
'
' Greatest Common Divisor
'
a%=24
b%=112
PRINT "GCD of ";a%;" and ";b%;" is ";@gcd(a%,b%)
'
' Function computes gcd
'
FUNCTION gcd(a%,b%)
LOCAL t%
'
WHILE b%<>0
t%=a%
a%=b%
b%=t% MOD b%
WEND
'
RETURN ABS(a%)
ENDFUNC
</lang>
 
=={{header|GML}}==
<syntaxhighlight lang="gml">
 
<lang GML>
var n,m,r;
n = max(argument0,argument1);
Line 2,494 ⟶ 3,754:
}
return a;
</syntaxhighlight>
</lang>
 
=={{header|gnuplot}}==
<langsyntaxhighlight lang="gnuplot">gcd (a, b) = b == 0 ? a : gcd (b, a % b)</langsyntaxhighlight>
Example:
<syntaxhighlight lang ="gnuplot">print gcd (111111, 1111)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="text">11</langsyntaxhighlight>
 
=={{header|Go}}==
===Binary Euclidian===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,547 ⟶ 3,807:
}
}
</syntaxhighlight>
</lang>
{{out|Output for Binary Euclidian algorithm}}
<pre>
Line 2,554 ⟶ 3,814:
</pre>
===Iterative===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,569 ⟶ 3,829:
fmt.Println(gcd(49865, 69811))
}
</syntaxhighlight>
</lang>
===Builtin===
(This is just a wrapper for <tt>big.GCD</tt>)
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,586 ⟶ 3,846:
fmt.Println(gcd(33, 77))
fmt.Println(gcd(49865, 69811))
}</langsyntaxhighlight>
{{out|Output in either case}}
<pre>
Line 2,594 ⟶ 3,854:
 
=={{header|Golfscript}}==
<langsyntaxhighlight lang="golfscript">;'2706 410'
~{.@\%.}do;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,603 ⟶ 3,863:
=={{header|Groovy}}==
===Recursive===
<langsyntaxhighlight lang="groovy">def gcdR
gcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcdR(n, m%n) }</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="groovy">def gcdI = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : { while(m%n != 0) { t=n; n=m%n; m=t }; n }() }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">println " R I"
println "gcd(28, 0) = ${gcdR(28, 0)} == ${gcdI(28, 0)}"
println "gcd(0, 28) = ${gcdR(0, 28)} == ${gcdI(0, 28)}"
Line 2,618 ⟶ 3,878:
println "gcd(28, 70) = ${gcdR(28, 70)} == ${gcdI(28, 70)}"
println "gcd(800, 70) = ${gcdR(800, 70)} == ${gcdI(800, 70)}"
println "gcd(27, -70) = ${gcdR(27, -70)} == ${gcdI(27, -70)}"</langsyntaxhighlight>
 
Output:
Line 2,630 ⟶ 3,890:
gcd(800, 70) = 10 == 10
gcd(27, -70) = 1 == 1</pre>
 
=={{header|GW-BASIC}}==
<lang gwbasic>10 INPUT A, B
20 IF A < 0 THEN A = -A
30 IF B < 0 THEN B = -B
40 GOTO 70
50 PRINT A
60 END
70 IF B = 0 THEN GOTO 50
80 TEMP = B
90 B = A MOD TEMP
100 A = TEMP
110 GOTO 70</lang>
 
=={{header|Haskell}}==
 
That is already available as the function ''gcd'' in the Prelude. Here's the implementation, with one name adjusted to avoid a Wiki formatting glitch:
 
<langsyntaxhighlight lang="haskell">gcd :: (Integral a) => a -> a -> a
gcd x y = gcd_ (abs x) (abs y)
where
gcd_ a 0 = a
gcd_ a b = gcd_ b (a `rem` b)</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">FUNCTION gcd(a, b)
IF(b == 0) THEN
gcd = ABS(a)
Line 2,668 ⟶ 3,914:
ENDDO
ENDIF
END</langsyntaxhighlight>
 
 
=={{header|Hoon}}==
 
<syntaxhighlight lang="hoon">::
:: Greatest common divisor (gcd), Euclid's algorithm.
::
|= [a=@ud b=@ud]
^- @ud
?> (gth b 0)
?: =((mod a b) 0)
b
$(a b, b (mod a b))</syntaxhighlight>
 
<pre>
An example of use at dojo (assuming the gate is pinned as gcd):
> (gcd 123 36)
3
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link numbers # gcd is part of the Icon Programming Library
procedure main(args)
write(gcd(arg[1], arg[2])) | "Usage: gcd n m")
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/procs/numbers.htm numbers] implements this as:
 
<langsyntaxhighlight Iconlang="icon">procedure gcd(i,j) #: greatest common divisor
local r
 
Line 2,689 ⟶ 3,954:
j := r
}
end</langsyntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang J="j">x+.y</langsyntaxhighlight>
 
For example:
 
<langsyntaxhighlight Jlang="j"> 12 +. 30
6</langsyntaxhighlight>
 
Note that <code>+.</code> is a single, two character token. GCD is a primitive in J (and anyone that has studied the right kind of mathematics should instantly recognize why the same operation is used for both GCD and OR -- among other things, GCD and boolean OR both have the same identity element: 0, and of course they produce the same numeric results on the same arguments (when we are allowed to use the usual 1 bit implementation of 0 and 1 for false and true) - more than that, though, GCD corresponds to George Boole's original "Boolean Algebra" (as it was later called). The redefinition of "Boolean algebra" to include logical negation came much later, in the 20th century).
Line 2,703 ⟶ 3,968:
gcd could also be defined recursively, if you do not mind a little inefficiency:
 
<langsyntaxhighlight Jlang="j">gcd=: (| gcd [)^:(0<[)&|</langsyntaxhighlight>
 
=={{header|Java}}==
From ''javax.swing.table.DefaultTableModel''
<syntaxhighlight lang="java">
/* recursive */
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
</syntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="java">public static long gcd(long a, long b){
long factor= Math.min(a, b);
for(long loop= factor;loop > 1;loop--){
Line 2,715 ⟶ 3,988:
}
return 1;
}</langsyntaxhighlight>
 
===Iterative Euclid's Algorithm===
<langsyntaxhighlight lang="java">
public static int gcd(int a, int b) //valid for positive integers.
{
Line 2,729 ⟶ 4,002:
return a;
}
</syntaxhighlight>
</lang>
 
===Optimized Iterative===
<langsyntaxhighlight lang="java">
static int gcd(int a,int b)
{
Line 2,741 ⟶ 4,014:
return 1;
}
</syntaxhighlight>
</lang>
 
===Iterative binary algorithm===
{{trans|C/C++}}
<langsyntaxhighlight lang="java">public static long gcd(long u, long v){
long t, k;
Line 2,774 ⟶ 4,047:
}
return u * k;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="java">public static long gcd(long a, long b){
if(a == 0) return b;
if(b == 0) return a;
if(a > b) return gcd(b, a % b);
return gcd(a, b % a);
}</langsyntaxhighlight>
===Built-in===
<langsyntaxhighlight lang="java">import java.math.BigInteger;
 
public static long gcd(long a, long b){
return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue();
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Iterative implementation
<langsyntaxhighlight lang="javascript">function gcd(a,b) {
a = Math.abs(a);
b = Math.abs(b);
Line 2,807 ⟶ 4,080:
if (b === 0) { return a; }
}
}</langsyntaxhighlight>
 
Recursive.
<langsyntaxhighlight lang="javascript">function gcd_rec(a, b) {
return b ? gcd_rec(b, a % b) : Math.abs(a);
}</langsyntaxhighlight>
 
Implementation that works on an array of integers.
<langsyntaxhighlight lang="javascript">function GCD(arr) {
var i, y,
n = arr.length,
Line 2,833 ⟶ 4,106:
//For example:
GCD([57,0,-45,-18,90,447]); //=> 3
</syntaxhighlight>
</lang>
 
=={{header|Joy}}==
<langsyntaxhighlight lang="joy">DEFINE gcd == [0 >] [dup rollup rem] while pop.</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def recursive_gcd(a; b):
if b == 0 then a
else recursive_gcd(b; a % b)
end ;</langsyntaxhighlight>Recent versions of jq include support for tail recursion optimization for arity-0 filters (which can be thought of as arity-1 functions), so here is an implementation that takes advantage of that optimization. Notice that the subfunction, rgcd, can be easily derived from recursive_gcd above by moving the arguments to the input:<langsyntaxhighlight lang="jq">def gcd(a; b):
# The subfunction expects [a,b] as input
# i.e. a ~ .[0] and b ~ .[1]
Line 2,848 ⟶ 4,121:
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ;</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 2,859 ⟶ 4,132:
1</pre>
The actual implementation of this function in Julia 0.2's standard library is reproduced here:
<langsyntaxhighlight lang="julia">function gcd{T<:Integer}(a::T, b::T)
neg = a < 0
while b != 0
Line 2,868 ⟶ 4,141:
g = abs(a)
neg ? -g : g
end</langsyntaxhighlight>
(For arbitrary-precision integers, Julia calls a different implementation from the GMP library.)
 
=={{header|K}}==
===K3===
<lang K>gcd:{:[~x;y;_f[y;x!y]]}</lang>
{{works with|Kona}}
<syntaxhighlight lang="k">gcd:{:[~x;y;_f[y;x!y]]}</syntaxhighlight>
===K6===
{{works with|ngn/k}}
<syntaxhighlight lang="k">gcd:{$[~x;y;o[x!y;x]]}</syntaxhighlight>
 
=={{header|Klong}}==
<langsyntaxhighlight Klang="k">gcd::{:[~x;y:|~y;x:|x>y;.f(y;x!y);.f(x;y!x)]}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Recursive one line solution:
<langsyntaxhighlight lang="kotlin">tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a % b)</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
Line 2,888 ⟶ 4,166:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
 
{def gcd
Line 2,919 ⟶ 4,197:
{S.map {GCD 123} {S.serie 1 30}}
-> 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
Line 2,925 ⟶ 4,203:
{{trans|Clojure}}
 
<langsyntaxhighlight lang="lisp">
> (defun gcd
"Get the greatest common divisor."
((a 0) a)
((a b) (gcd b (rem a b))))
</syntaxhighlight>
</lang>
 
Usage:
Line 2,943 ⟶ 4,221:
17
</pre>
 
=={{header|Liberty BASIC}}==
<lang lb>'iterative Euclid algorithm
print GCD(-2,16)
end
 
function GCD(a,b)
while b
c = a
a = b
b = c mod b
wend
GCD = abs(a)
end function
</lang>
 
=={{header|Limbo}}==
<syntaxhighlight lang="limbo">gcd(x: int, y: int): int
 
<lang Limbo>gcd(x: int, y: int): int
{
if(y == 0)
Line 2,967 ⟶ 4,229:
return gcd(y, x % y);
}
</syntaxhighlight>
</lang>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function gcd x,y
repeat until y = 0
put x mod y into z
Line 2,977 ⟶ 4,239:
end repeat
return x
end gcd</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to gcd :a :b
if :b = 0 [output :a]
output gcd :b modulo :a :b
end</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
HOW IZ I gcd YR a AN YR b
Line 3,023 ⟶ 4,285:
VISIBLE I IZ gcd YR 40902 AN YR 24140 MKAY
 
KTHXBYE</langsyntaxhighlight>
[https://tio.run/##jVJNU8IwFDw3v2KPOoNOwV48Oal8NAMlTpuK5ZZARMcydVrw79ekrUhlRHNJ3kt2377Ny/Jsla91VQWUoX99Q0jAF2BLMGxWa6QRJOjc7oo4EhF8NplE4OMm/xDxYTIVh/iqD8AXC0CqMs/2O40Pme018mdI4qhjAvWDQP1FYBT4XASI6ShsyqkeOKJZekccJ6X2ZA7OmCfzYS3dRJzdn8Dc8zB1ClP/gMlfYF3HDpLRrLrXrXzTKPeFNm9eS@xeNDJZbHRh276QPajLTk2GgMag2OntO5hY1rXr77Haa5vtVSuIOCwEqz8xy3ObPcFbmEWFfPitlDSULdMZM46Ude1o/DDVeSIE/RIAwsZIDFeKmBPyyGLmz0Zm4szYtUPnubfuoB28gdf3XIRTmhIyFcGTn46q6hM Try it online!]
 
=={{header|LSE}}==
<syntaxhighlight lang="lse">(*
<lang LSE>(*
** MÉTHODE D'EUCLIDE POUR TROUVER LE PLUS GRAND DIVISEUR COMMUN D'UN
** NUMÉRATEUR ET D'UN DÉNOMINATEUR.
Line 3,051 ⟶ 4,313:
&DEMO(6144,8192)
&DEMO(100,5)
&DEMO(7,23)</langsyntaxhighlight>
 
Resultats:
Line 3,063 ⟶ 4,325:
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">function gcd(a,b)
if b ~= 0 then
return gcd(b, a % b)
Line 3,077 ⟶ 4,339:
demo(100, 5)
demo(5, 100)
demo(7, 23)</langsyntaxhighlight>
 
Output:
Line 3,087 ⟶ 4,349:
 
Faster iterative solution of Euclid:
<langsyntaxhighlight lang="lua">function gcd(a,b)
while b~=0 do
a,b=b,a%b
Line 3,093 ⟶ 4,355:
return math.abs(a)
end
</syntaxhighlight>
</lang>
 
=={{header|Lucid}}==
===dataflow algorithm===
<langsyntaxhighlight lang="lucid">gcd(n,m) where
z = [% n, m %] fby if x > y then [% x - y, y %] else [% x, y - x%] fi;
x = hd(z);
y = hd(tl(z));
gcd(n, m) = (x asa x*y eq 0) fby eod;
end</langsyntaxhighlight>
 
=={{header|Luck}}==
<langsyntaxhighlight lang="luck">function gcd(a: int, b: int): int = (
if a==0 then b
else if b==0 then a
else if a>b then gcd(b, a % b)
else gcd(a, b % a)
)</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
gcd=lambda (u as long, v as long) -> {
=if(v=0&->abs(u), lambda(v, u mod v))
Line 3,132 ⟶ 4,394:
CheckGCD gcd
CheckGCD gcd_Iterative
</syntaxhighlight>
</lang>
 
=={{header|m4}}==
This should work in any POSIX-compliant m4. I have tested it with GNU m4, OpenBSD m4, and Heirloom Devtools m4. It is Euler’s algorithm.
<syntaxhighlight lang="m4">divert(-1)
define(`gcd',
`ifelse(eval(`0 <= (' $1 `)'),`0',`gcd(eval(`-(' $1 `)'),eval(`(' $2 `)'))',
eval(`0 <= (' $2 `)'),`0',`gcd(eval(`(' $1 `)'),eval(`-(' $2 `)'))',
eval(`(' $1 `) == 0'),`0',`gcd(eval(`(' $2 `) % (' $1 `)'),eval(`(' $1 `)'))',
eval(`(' $2 `)'))')
divert`'dnl
dnl
gcd(0, 0) = 0
gcd(24140, 40902) = 34
gcd(-24140, -40902) = 34
gcd(-40902, 24140) = 34
gcd(40902, -24140) = 34</syntaxhighlight>
 
{{out}}
<pre>0 = 0
34 = 34
34 = 34
34 = 34
34 = 34</pre>
 
=={{header|Maple}}==
To compute the greatest common divisor of two integers in Maple, use the procedure igcd.
 
<syntaxhighlight lang Maple="maple">igcd( a, b )</langsyntaxhighlight>
 
For example,
<syntaxhighlight lang="maple">
<lang Maple>
> igcd( 24, 15 );
3
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang ="mathematica">GCD[a, b]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function [gcdValue] = greatestcommondivisor(integer1, integer2)
gcdValue = gcd(integer1, integer2);</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* There is a function gcd(a, b) in Maxima, but one can rewrite it */
gcd2(a, b) := block([a: abs(a), b: abs(b)], while b # 0 do [a, b]: [b, mod(a, b)], a)$
 
/* both will return 2^97 * 3^48 */
gcd(100!, 6^100), factor;
gcd2(100!, 6^100), factor;</langsyntaxhighlight>
 
=={{header|MAXScript}}==
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="maxscript">fn gcdIter a b =
(
while b > 0 do
Line 3,171 ⟶ 4,456:
)
abs a
)</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="maxscript">fn gcdRec a b =
(
if b > 0 then gcdRec b (mod a b) else abs a
)</langsyntaxhighlight>
 
=={{header|Mercury}}==
===Recursive Euclid algorithm===
<langsyntaxhighlight Mercurylang="mercury">:- module gcd.
 
:- interface.
Line 3,191 ⟶ 4,476:
 
:- pragma memo(gcd/2).
gcd(A, B) = (if B = integer(0) then A else gcd(B, A mod B)).</langsyntaxhighlight>
 
An example console program to demonstrate the gcd module:
<langsyntaxhighlight Mercurylang="mercury">:- module test_gcd.
 
:- interface.
Line 3,221 ⟶ 4,506:
Fmt = integer.to_string,
GCD = gcd(A, B),
io.format("gcd(%s, %s) = %s\n", [s(Fmt(A)), s(Fmt(B)), s(Fmt(GCD))], !IO).</langsyntaxhighlight>
 
Example output:
<langsyntaxhighlight Bashlang="bash">gcd(70000000000000000000000, 60000000000000000000000000) = 10000000000000000000000</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.37.0}}
<syntaxhighlight lang="min">((dup 0 !=) (swap over mod) while pop abs) ^gcd</syntaxhighlight>
 
=={{header|MINIL}}==
<langsyntaxhighlight lang="minil">// Greatest common divisor
00 0E GCD: ENT R0
01 1E ENT R1
Line 3,240 ⟶ 4,529:
0A 1D Stop: DEC R1
0B C2 JNZ Again
0C 80 JZ GCD // Display GCD in R0</langsyntaxhighlight>
 
=={{header|MiniScript}}==
Using an iterative Euclidean algorithm:
<langsyntaxhighlight MiniScriptlang="miniscript">gcd = function(a, b)
while b
temp = b
Line 3,253 ⟶ 4,542:
end function
 
print gcd(18,12)</langsyntaxhighlight>
{{output}}
<pre>6</pre>
 
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">function var int: gcd(int:a2,int:b2) =
let {
int:a1 = max(a2,b2);
int:b1 = min(a2,b2);
array[0..a1,0..b1] of var int: gcd;
constraint forall(a in 0..a1)(
forall(b in 0..b1)(
gcd[a,b] ==
if (b == 0) then
a
else
gcd[b, a mod b]
endif
)
)
} in gcd[a1,b1];
var int: gcd1 = gcd(8,12);
solve satisfy;
output [show(gcd1),"\n"];</syntaxhighlight>
{{output}}
<pre>6</pre>
 
=={{header|MIPS Assembly}}==
<langsyntaxhighlight lang="mips">gcd:
# a0 and a1 are the two integer parameters
# return value is in v0
Line 3,271 ⟶ 4,584:
done:
move $v0, $t0
jr $ra</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
Line 3,283 ⟶ 4,596:
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">fun gcd (a, 0) = a
| (0, b) = b
| (a, b) where (a < b)
Line 3,289 ⟶ 4,602:
| (a, b) = gcd (b, a rem b)
 
</syntaxhighlight>
</lang>
 
==={{header|ML}} / {{header|Standard ML}}===
 
<lang sml>fun gcd a 0 = a
See also [[#Standard ML]].
| gcd a b = gcd b (a mod b)</lang>
 
<syntaxhighlight lang="sml">fun gcd a 0 = a
| gcd a b = gcd b (a mod b)</syntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ggTkgV;
 
FROM InOut IMPORT ReadCard, WriteCard, WriteLn, WriteString, WriteBf;
Line 3,321 ⟶ 4,637:
WriteString ("u ="); WriteCard (u, 6); WriteLn;
WriteString ("v ="); WriteCard (v , 6); WriteLn
END ggTkgV.</langsyntaxhighlight>
Producing the output
<langsyntaxhighlight Modulalang="modula-2">jan@Beryllium:~/modula/Wirth/PIM$ ggtkgv
x = 12
y = 20
Line 3,336 ⟶ 4,652:
kgV = 10455
u = 13773
v = 7137</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE GCD EXPORTS Main;
 
IMPORT IO, Fmt;
Line 3,360 ⟶ 4,676:
IO.Put("GCD of 5, 100 is " & Fmt.Int(GCD(5, 100)) & "\n");
IO.Put("GCD of 7, 23 is " & Fmt.Int(GCD(7, 23)) & "\n");
END GCD.</langsyntaxhighlight>
 
Output:
Line 3,368 ⟶ 4,684:
GCD of 7, 23 is 1
</pre>
 
=={{header|Monicelli}}==
<syntaxhighlight lang="monicelli">
#main function (needs two ints from stdin)
Lei ha clacsonato bitumatissimi cari amici ospiti
voglio arrivata, Necchi bitumati qui tra noi benvenuti ENERGIAAh
voglio espertizzata, Necchi
mi porga arrivata mi porga espertizzata bitumata mi raccomando
voglio garantita, Necchi come se fosse prematurata la supercazzola accanita con arrivata, espertizzata o scherziamo?
brematurata la supercazzola novella o scherziamo? bitumata ma dai
garantita a posterdati
# gcd function
blinda la supercazzola Necchi accanita con visibilio Necchi, sgomento Necchi o scherziamo?
voglio la catarsi, Necchi bituma, e come bituma lui non bituma nessuno
voglio l'entusiasmo, Necchi bituma, chi di bituma vive bitumato muore
che cos'è il visibilio? sgomento: vaffanzum visibilio!
o magari maggiore di sgomento: catarsi come fosse visibilio meno sgomento bitumato ma non troppo
entusiasmo come fosse sgomento bitumato anche piu del necessario
o tarapia tapioco: catarsi come fosse sgomento meno il visibilio bitumante dai tempi andati
entusiasmo come fosse visibilio e velocità di esecuzione
voglio la spensierataggine, Necchi come fosse prematurata la supercazzola accanita con catarsi, entusiasmo o scherziamo?
vaffanzum la spensierataggine!
# prints new line
blinda la supercazzola novella o scherziamo?
voglio novita, Mascetti come se fosse 10 bituma come fosse una lungaggine, uno scherzo di mano
novita a posterdati!
</syntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">
<lang MUMPS>
GCD(A,B)
QUIT:((A/1)'=(A\1))!((B/1)'=(B\1)) 0
Line 3,377 ⟶ 4,720:
IF B'=0
FOR SET T=A#B,A=B,B=T QUIT:B=0 ;ARGUEMENTLESS FOR NEEDS TWO SPACES
QUIT A</langsyntaxhighlight>
 
Ouput:
Line 3,391 ⟶ 4,734:
=={{header|MySQL}}==
 
<langsyntaxhighlight lang="mysql">
DROP FUNCTION IF EXISTS gcd;
DELIMITER |
Line 3,416 ⟶ 4,759:
 
SELECT gcd(12345, 9876);
</syntaxhighlight>
</lang>
 
+------------------+
Line 3,428 ⟶ 4,771:
{{trans|Java}}
===Iterative===
<langsyntaxhighlight Nanoquerylang="nanoquery">def gcd(a, b)
factor = a.min(b)
 
Line 3,438 ⟶ 4,781:
 
return 1
end</langsyntaxhighlight>
 
===Iterative Euclid's Method===
<langsyntaxhighlight Nanoquerylang="nanoquery">def gcd_euclid(a, b)
while b > 0
c = a % b
Line 3,448 ⟶ 4,791:
end
return a
end</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,458 ⟶ 4,801:
return
 
-- 09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Euclid's algorithm - iterative implementation
method gcdEucidI(a_, b_) public static
Line 3,468 ⟶ 4,811:
return a_
 
-- 09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Euclid's algorithm - recursive implementation
method gcdEucidR(a_, b_) public static
Line 3,474 ⟶ 4,817:
return a_
 
-- 09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
-- pairs of numbers, each number in the pair separated by a colon, each pair separated by a comma
Line 3,520 ⟶ 4,863:
return
 
-- 09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method showResults(stem, title) public static
say
Line 3,531 ⟶ 4,874:
return
 
-- 09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)09:53, 27 August 2022 (UTC)~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method verifyResults(stem1, stem2) public static returns boolean
if stem1[0] \= stem2[0] then signal BadArgumentException
Line 3,544 ⟶ 4,887:
end i_
return verified
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,583 ⟶ 4,926:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(gcd 12 36)
→ 12</langsyntaxhighlight>
 
=={{header|Nial}}==
Nial provides gcd in the standard lib.
<langsyntaxhighlight lang="nial">|loaddefs 'niallib/gcd.ndf'
|gcd 6 4
=2</langsyntaxhighlight>
 
defining it for arrays
<langsyntaxhighlight lang="nial"># red is the reduction operator for a sorted list
# one is termination condition
red is cull filter (0 unequal) link [mod [rest, first] , first]
one is or [= [1 first, tally], > [2 first, first]]
gcd is fork [one, first, gcd red] sort <=</langsyntaxhighlight>
 
Using it
<langsyntaxhighlight lang="nial">|gcd 9 6 3
=3</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Pascal}}
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="nim">func gcd_recursive*(u, v: SomeSignedInt): int64 =
if u mod v != 0:
result = gcd_recursive(v, u mod v)
Line 3,615 ⟶ 4,958:
import strformat
let (x, y) = (49865, 69811)
echo &"gcd({x}, {y}) = {gcd_recursive(49865, 69811)}"</langsyntaxhighlight>
 
{{out}}
Line 3,621 ⟶ 4,964:
 
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="nim">func gcd_iterative*(u, v: SomeSignedInt): int64 =
var u = u
var v = v
Line 3,632 ⟶ 4,975:
import strformat
let (x, y) = (49865, 69811)
echo &"gcd({x}, {y}) = {gcd_iterative(49865, 69811)}")</langsyntaxhighlight>
 
{{out}}
Line 3,638 ⟶ 4,981:
 
===Iterative binary algorithm===
<langsyntaxhighlight lang="nim">template isEven(n: int64): bool = (n and 1) == 0
 
func gcd_binary*(u, v: int64): int64 =
Line 3,664 ⟶ 5,007:
import strformat
let (x, y) = (49865, 69811)
echo &"gcd({x}, {y}) = {gcd_binary(49865, 69811)}"</langsyntaxhighlight>
{{out}}
<pre>gcd(49865, 69811) = 9973</pre>
Line 3,670 ⟶ 5,013:
=={{header|Oberon-2}}==
Works with oo2c version 2
<langsyntaxhighlight lang="oberon2">
MODULE GCD;
(* Greatest Common Divisor *)
Line 3,693 ⟶ 5,036:
Out.String("GCD of 40902 and 24140 : ");Out.LongInt(Gcd(40902,24140),4);Out.Ln
END GCD.
</syntaxhighlight>
</lang>
Output:<br/>
<pre>
Line 3,704 ⟶ 5,047:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class GDC {
Line 3,728 ⟶ 5,071:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec gcd a b = function
if | 0 -> a = 0 then b
| b -> gcd b (a mod b)</syntaxhighlight>
else if b = 0 then a
else if a > b then gcd b (a mod b)
else gcd a (b mod a)</lang>
 
A little more idiomatic version:
<lang ocaml>let rec gcd1 a b =
match (a mod b) with
0 -> b
| r -> gcd1 b r</lang>
 
=== Built-in ===
<langsyntaxhighlight lang="ocaml">#load "nums.cma";;
open Big_int;;
let gcd a b =
int_of_big_int (gcd_big_int (big_int_of_int a) (big_int_of_int b))</langsyntaxhighlight>
 
=={{header|Octave}}==
 
<langsyntaxhighlight lang="octave">r = gcd(a, b)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
gcd is already defined into Integer class :
<syntaxhighlight lang Oforth="oforth">128 96 gcd</langsyntaxhighlight>
 
Source of this method is (see Integer.of file) :
<langsyntaxhighlight Oforthlang="oforth">Integer method: gcd self while ( dup ) [ tuck mod ] drop ;</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(print (gcd 1071 1029))
; ==> 21
</syntaxhighlight>
</lang>
 
=={{header|Order}}==
{{trans|bc}}
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8gcd ORDER_PP_FN( \
8fn(8U, 8V, \
8if(8isnt_0(8V), 8gcd(8V, 8remainder(8U, 8V)), 8U)))
// No support for negative numbers</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {UnsafeGCD A B}
if B == 0 then
Line 3,794 ⟶ 5,129:
end
in
{Show {GCD 456 ~632}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">gcd(a,b)</langsyntaxhighlight>
 
[[PASCAL]]
Line 3,823 ⟶ 5,158:
===Recursive Euclid algorithm===
{{works with|Free Pascal|version 3.2.0 }}
<langsyntaxhighlight lang="pascal">
PROGRAM EXRECURGCD.PAS;
 
Line 3,851 ⟶ 5,186:
END.
 
</langsyntaxhighlight>JPD 2021/03/14
 
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="fortran">function gcd_iterative(u, v: longint): longint;
var
t: longint;
Line 3,865 ⟶ 5,200:
end;
gcd_iterative := abs(u);
end;</langsyntaxhighlight>
 
===Iterative binary algorithm===
<langsyntaxhighlight Pascallang="pascal">function gcd_binary(u, v: longint): longint;
var
t, k: longint;
Line 3,907 ⟶ 5,242:
gcd_binary := u * k;
end;
end;</langsyntaxhighlight>
 
Demo program:
 
<langsyntaxhighlight lang="pascal">Program GreatestCommonDivisorDemo(output);
begin
writeln ('GCD(', 49865, ', ', 69811, '): ', gcd_iterative(49865, 69811), ' (iterative)');
writeln ('GCD(', 49865, ', ', 69811, '): ', gcd_recursive(49865, 69811), ' (recursive)');
writeln ('GCD(', 49865, ', ', 69811, '): ', gcd_binary (49865, 69811), ' (binary)');
end.</langsyntaxhighlight>
Output:
<pre>GCD(49865, 69811): 9973 (iterative)
Line 3,925 ⟶ 5,260:
=={{header|Perl}}==
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="perl">sub gcd_iter($$) {
my ($u, $v) = @_;
while ($v) {
Line 3,931 ⟶ 5,266:
}
return abs($u);
}</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="perl">sub gcd($$) {
my ($u, $v) = @_;
if ($v) {
Line 3,941 ⟶ 5,276:
return abs($u);
}
}</langsyntaxhighlight>
 
===Iterative binary algorithm===
<langsyntaxhighlight lang="perl">sub gcd_bin($$) {
my ($u, $v) = @_;
$u = abs($u);
Line 3,973 ⟶ 5,308:
}
return $u * $k;
}</langsyntaxhighlight>
 
===Modules===
All three modules will take large integers as input, e.g.
<tt>gcd("68095260063025322303723429387", "51306142182612010300800963053")</tt>. Other possibilities are Math::Cephes euclid, Math::GMPz gcd and gcd_ui.
<langsyntaxhighlight lang="perl"># Fastest, takes multiple inputs
use Math::Prime::Util "gcd";
$gcd = gcd(49865, 69811);
Line 3,989 ⟶ 5,324:
use Math::Pari "gcd";
$gcd = gcd(49865, 69811)->pari2iv
</syntaxhighlight>
</lang>
 
===Notes on performance===
<langsyntaxhighlight lang="perl">use Benchmark qw(cmpthese);
use Math::BigInt;
use Math::Pari;
Line 4,006 ⟶ 5,341:
'gcd_pari' => sub { Math::Pari::gcd($u,$v)->pari2iv(); },
'gcd_mpu' => sub { Math::Prime::Util::gcd($u,$v); },
});</langsyntaxhighlight>
 
Output on 'Intel i3930k 4.2GHz' / Linux / Perl 5.20:
Line 4,023 ⟶ 5,358:
atom parameters allow greater precision, but any fractional parts are immediately and deliberately discarded.<br>
Actually, it is an autoinclude, reproduced below. The first parameter can be a sequence, in which case the second parameter (if provided) is ignored.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">u</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t</span>
Line 4,044 ⟶ 5,379:
<span style="color: #008080;">return</span> <span style="color: #000000;">u</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</langsyntaxhighlight>-->
Sample results
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">24</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">112</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 8</span>
Line 4,064 ⟶ 5,399:
<span style="color: #000080;font-style:italic;">-- 10000000000000000000</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">({</span><span style="color: #000000;">57</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">45</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">18</span><span style="color: #0000FF;">,</span><span style="color: #000000;">90</span><span style="color: #0000FF;">,</span><span style="color: #000000;">447</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- 3</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
 
===Iterative===
<langsyntaxhighlight lang="php">
function gcdIter($n, $m) {
while(true) {
Line 4,082 ⟶ 5,417:
}
}
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="php">
function gcdRec($n, $m)
{
Line 4,093 ⟶ 5,428:
return abs($n);
}
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de gcd (A B)
(until (=0 B)
(let M (% A B)
(setq A B B M) ) )
(abs A) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
GCD: procedure (a, b) returns (fixed binary (31)) recursive;
declare (a, b) fixed binary (31);
Line 4,112 ⟶ 5,447:
 
end GCD;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
===Built-in gcd===
<langsyntaxhighlight lang="pop11">gcd_n(15, 12, 2) =></langsyntaxhighlight>
 
Note: the last argument gives the number of other arguments (in
this case 2).
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="pop11">define gcd(k, l) -> r;
lvars k , l, r = l;
abs(k) -> k;
Line 4,130 ⟶ 5,465:
endwhile;
k -> r;
enddefine;</langsyntaxhighlight>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
/gcd {
{
Line 4,140 ⟶ 5,475:
} loop
}.
</syntaxhighlight>
</lang>
With no external lib, recursive
<langsyntaxhighlight lang="postscript">
/gcd {
dup 0 ne {
Line 4,148 ⟶ 5,483:
} { pop } ifelse
} def
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
===Recursive Euclid Algorithm===
<langsyntaxhighlight lang="powershell">function Get-GCD ($x, $y)
{
if ($x -eq $y) { return $y }
Line 4,169 ⟶ 5,504:
}
return $b
}</langsyntaxhighlight>
 
or shorter (taken from Python implementation)
<langsyntaxhighlight lang="powershell">function Get-GCD ($x, $y) {
if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }
}</langsyntaxhighlight>
 
===Iterative Euclid Algorithm===
 
based on Python implementation
<langsyntaxhighlight lang="powershell">
Function Get-GCD( $x, $y ) {
while ($y -ne 0) {
Line 4,186 ⟶ 5,521:
[Math]::abs($x)
}
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
===Recursive Euclid Algorithm===
<langsyntaxhighlight lang="prolog">gcd(X, 0, X):- !.
gcd(0, X, X):- !.
gcd(X, Y, D):- X > Y, !, Z is X mod Y, gcd(Y, Z, D).
gcd(X, Y, D):- Z is Y mod X, gcd(X, Z, D).</langsyntaxhighlight>
 
===Repeated Subtraction===
<langsyntaxhighlight lang="prolog">gcd(X, 0, X):- !.
gcd(0, X, X):- !.
gcd(X, Y, D):- X =< Y, !, Z is Y - X, gcd(X, Z, D).
gcd(X, Y, D):- gcd(Y, X, D).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
'''Iterative'''
<lang PureBasic>Procedure GCD(x, y)
Protected r
While y <> 0
r = x % y
x = y
y = r
Wend
ProcedureReturn y
EndProcedure</lang>
 
'''Recursive'''
<lang PureBasic>Procedure GCD(x, y)
Protected r
r = x % y
If (r > 0)
y = GCD(y, r)
EndIf
ProcedureReturn y
EndProcedure</lang>
 
=={{header|Purity}}==
<syntaxhighlight lang="purity">
<lang Purity>
data Iterate = f => FoldNat <const id, g => $g . $f>
 
Line 4,246 ⟶ 5,559:
 
data gcd = Iterate (gcd => uncurry (step (curry $gcd)))
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===Built-in===
{{works with|Python|2.6+}}
<syntaxhighlight lang ="python">from fractions import gcd</langsyntaxhighlight>
 
{{Works with|Python|3.7}}
(Note that '''fractions.gcd''' is now deprecated in Python 3)
<syntaxhighlight lang ="python">from math import gcd</langsyntaxhighlight>
 
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="python">def gcd_iter(u, v):
while v:
u, v = v, u % v
return abs(u)</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
'''Interpreter:''' [[Python]] 2.5
<langsyntaxhighlight lang="python">def gcd(u, v):
return gcd(v, u % v) if v else abs(u)</langsyntaxhighlight>
 
===Tests===
Line 4,282 ⟶ 5,595:
===Iterative binary algorithm===
See [[The Art of Computer Programming]] by Knuth (Vol.2)
<langsyntaxhighlight lang="python">def gcd_bin(u, v):
u, v = abs(u), abs(v) # u >= 0, v >= 0
if u < v:
Line 4,304 ⟶ 5,617:
v = -t
t = u - v
return u * k</langsyntaxhighlight>
 
===Notes on performance===
Line 4,312 ⟶ 5,625:
 
<tt>gcd_bin(40902, 24140)</tt> takes us about '''41''' µsec
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
(define gcd
A 0 -> A
A B -> (gcd B (MOD A B)))
</syntaxhighlight>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
<lang Quackery>
[ [ dup while
tuck mod again ]
drop abs ] is gcd ( n n --> n )
</syntaxhighlight>
</lang>
 
=={{header|Qi}}==
<lang Qi>
(define gcd
A 0 -> A
A B -> (gcd B (MOD A B)))
</lang>
 
=={{header|R}}==
Recursive:
<langsyntaxhighlight Rlang="r">"%gcd%" <- function(u, v) {
ifelse(u %% v != 0, v %gcd% (u%%v), v)
}</langsyntaxhighlight>
Iterative:
<langsyntaxhighlight Rlang="r">"%gcd%" <- function(v, t) {
while ( (c <- v%%t) != 0 ) {
v <- t
Line 4,339 ⟶ 5,652:
}
t
}</langsyntaxhighlight>
{{out}}
Same either way.
Line 4,351 ⟶ 5,664:
Racket provides a built-in gcd function. Here's a program that computes the gcd of 14 and 63:
 
<langsyntaxhighlight lang="racket">#lang racket
 
(gcd 14 63)</langsyntaxhighlight>
 
Here's an explicit implementation. Note that since Racket is tail-calling, the memory behavior of this program is "loop-like", in the sense that this program will consume no more memory than a loop-based implementation.
 
<langsyntaxhighlight lang="racket">#lang racket
 
;; given two nonnegative integers, produces their greatest
Line 4,373 ⟶ 5,686:
(* 3 3 7))
(check-equal? (gcd 0 14) 14)
(check-equal? (gcd 13 0) 13))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 4,379 ⟶ 5,692:
 
===Iterative===
<syntaxhighlight lang="raku" perl6line>sub gcd (Int $a is copy, Int $b is copy) {
$a & $b == 0 and fail;
($a, $b) = ($b, $a % $b) while $b;
return abs $a;
}</langsyntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="raku" perl6line>multi gcd (0, 0) { fail }
multi gcd (Int $a, 0) { abs $a }
multi gcd (Int $a, Int $b) { gcd $b, $a % $b }</langsyntaxhighlight>
 
===Recursive(inline coderef)===
<syntaxhighlight lang="raku" line>{ $^b ?? &?BLOCK( $^b, $^a % $^b ) !! $^a }</syntaxhighlight>
 
===Concise===
<syntaxhighlight lang="raku" perl6line>my &gcd = { ($^a.abs, $^b.abs, * % * ... 0)[*-2] }</langsyntaxhighlight>
 
===Actually, it's a built-in infix===
<syntaxhighlight lang="raku" perl6line>my $gcd = $a gcd $b;</langsyntaxhighlight>
Because it's an infix, you can use it with various meta-operators:
<syntaxhighlight lang="raku" perl6line>[gcd] @list; # reduce with gcd
@alist Zgcd @blist; # lazy zip with gcd
@alist Xgcd @blist; # lazy cross with gcd
@alist »gcd« @blist; # parallel gcd</langsyntaxhighlight>
 
=={{header|Rascal}}==
 
===Iterative Euclidean algorithm===
<langsyntaxhighlight lang="rascal">
public int gcd_iterative(int a, b){
if(a == 0) return b;
Line 4,412 ⟶ 5,728:
return a;
}
</syntaxhighlight>
</lang>
An example:
<langsyntaxhighlight lang="rascal">
rascal>gcd_iterative(1989, 867)
int: 51
</syntaxhighlight>
</lang>
 
===Recursive Euclidean algorithm===
<langsyntaxhighlight lang="rascal">
public int gcd_recursive(int a, b){
return (b == 0) ? a : gcd_recursive(b, a%b);
}
</syntaxhighlight>
</lang>
An example:
<langsyntaxhighlight lang="rascal">
rascal>gcd_recursive(1989, 867)
int: 51
</syntaxhighlight>
</lang>
 
=={{header|Raven}}==
===Recursive Euclidean algorithm===
<langsyntaxhighlight Ravenlang="raven">define gcd use $u, $v
$v 0 > if
$u $v % $v gcd
Line 4,439 ⟶ 5,755:
$u abs
 
24140 40902 gcd</langsyntaxhighlight>
{{out}}<pre>34</pre>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">gcd: func [
{Returns the greatest common divisor of m and n.}
m [integer!]
Line 4,456 ⟶ 5,772:
]
m
]</langsyntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Gcd 3528 3780>>;
};
 
Gcd {
s.M 0 = s.M;
s.M s.N = <Gcd s.N <Mod s.M s.N>>;
};</syntaxhighlight>
{{out}}
<pre>252</pre>
 
=={{header|Retro}}==
This is from the math extensions library.
 
<langsyntaxhighlight Retrolang="retro">: gcd ( ab-n ) [ tuck mod dup ] while drop ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 4,468 ⟶ 5,796:
<br>argument(s), &nbsp; making it easier to use when computing Frobenius numbers &nbsp; (also known as &nbsp; ''postage stamp'' &nbsp; or &nbsp;
<br>''coin'' &nbsp; numbers).
<langsyntaxhighlight lang="rexx">/*REXX program calculates the GCD (Greatest Common Divisor) of any number of integers.*/
numeric digits 2000 /*handle up to 2k decimal dig integers.*/
call gcd 0 0 ; call gcd 55 0 ; call gcd 0 66
Line 4,485 ⟶ 5,813:
 
say 'GCD (Greatest Common Divisor) of ' translate(space($),",",' ') " is " x
return x</langsyntaxhighlight>
'''output'''
<pre>
Line 4,506 ⟶ 5,834:
===version 2===
Recursive function (as in PL/I):
<syntaxhighlight lang="rexx">
<lang REXX>
/* REXX ***************************************************************
* using PL/I code extended to many arguments
Line 4,552 ⟶ 5,880:
Parse Arg a,b
if b = 0 then return abs(a)
return GCD(b,a//b)</langsyntaxhighlight>
Output:
<pre>
Line 4,571 ⟶ 5,899:
Considerably faster than version 1 (and version 2)
<br>See http://rosettacode.org/wiki/Least_common_multiple#REXX for reasoning.
<langsyntaxhighlight lang="rexx">gcd: procedure
x=abs(arg(1))
do j=2 to arg()
Line 4,583 ⟶ 5,911:
end
end
return x</langsyntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="text">
see gcd (24, 32)
func gcd gcd, b
Line 4,595 ⟶ 5,923:
end
return gcd
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
≪ '''WHILE''' DUP '''REPEAT''' SWAP OVER MOD '''END''' DROP ABS ≫ '<span style="color:blue">'''GCD'''</span>' STO
 
40902 24140 <span style="color:blue">'''GCD'''</span>
'''Output:'''
<span style="color:grey">1:</span> 34
===Using unsigned integers===
≪ DUP2 < ≪ SWAP ≫ '''IFT'''
'''WHILE''' DUP B→R '''REPEAT''' SWAP OVER / LAST ROT * - '''END''' DROP
≫ '<span style="color:blue">'''GCD'''</span>' STO
 
#40902d #24140d <span style="color:blue">'''GCD'''</span>
'''Output:'''
<span style="color:grey">1:</span> #34d
 
=={{header|Ruby}}==
Line 4,601 ⟶ 5,944:
That is already available as the ''gcd'' method of integers:
 
<langsyntaxhighlight lang="ruby">
40902.gcd(24140) # => 34</langsyntaxhighlight>
 
Here's an implementation:
<langsyntaxhighlight lang="ruby">def gcd(u, v)
u, v = u.abs, v.abs
while v > 0
Line 4,611 ⟶ 5,954:
end
u
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<lang Runbasic>print abs(gcd(-220,160))
function gcd(gcd,b)
while b
c = gcd
gcd = b
b = c mod b
wend
end function </lang>
 
=={{header|Rust}}==
===num crate===
<langsyntaxhighlight lang="rust">extern crate num;
use num::integer::gcd;</langsyntaxhighlight>
 
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="rust">fn gcd(mut m: i32, mut n: i32) -> i32 {
while m != 0 {
let old_m = m;
Line 4,636 ⟶ 5,969:
}
n.abs()
}</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="rust">fn gcd(m: i32, n: i32) -> i32 {
if m == 0 {
n.abs()
Line 4,645 ⟶ 5,978:
gcd(n % m, m)
}
}</langsyntaxhighlight>
 
===Stein's Algorithm===
Stein's algorithm is very much like Euclid's except that it uses bitwise operators (and consequently slightly more performant) and the integers must be unsigned. The following is a recursive implementation that leverages Rust's pattern matching.
 
<langsyntaxhighlight lang="rust">use std::cmp::{min, max};
fn gcd(a: usize, b: usize) -> usize {
match ((a, b), (a & 1, b & 1)) {
Line 4,662 ⟶ 5,995:
_ => unreachable!(),
}
}</langsyntaxhighlight>
 
===Tests===
<langsyntaxhighlight lang="rust">
println!("{}",gcd(399,-3999));
println!("{}",gcd(0,3999));
Line 4,672 ⟶ 6,005:
3
3999
13</langsyntaxhighlight>
 
=={{header|Sass/SCSS}}==
Line 4,678 ⟶ 6,011:
Iterative Euclid's Algorithm
 
<langsyntaxhighlight lang="coffeescript">
@function gcd($a,$b) {
@while $b > 0 {
Line 4,687 ⟶ 6,020:
@return $a;
}
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
{{trans|bc}}
<langsyntaxhighlight lang="sather">class MATH is
 
gcd_iter(u, v:INT):INT is
Line 4,742 ⟶ 6,075:
end;
 
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
a ::= 40902;
Line 4,754 ⟶ 6,087:
#OUT + a.gcd(b) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
<lang basic>
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
 
rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
var r, temp = integer
if x < y then
begin
temp = x
x = y
y = temp
end
r = mod(x, y)
while r <> 0 do
begin
x = y
y = r
r = mod(x, y)
end
end = y
 
rem - exercise the function
 
print "The GCD of 21 and 35 is"; gcd(21,35)
print "The GCD of 23 and 35 is"; gcd(23,35)
print "The GCD of 1071 and 1029 is"; gcd(1071, 1029)
print "The GCD of 3528 and 3780 is"; gcd(3528,3780)
 
end
</lang>
{{out}}
<pre>The GCD of 21 and 35 is 7
The GCD of 23 and 35 is 1
The GCD of 1071 and 1029 is 21
The GCD of 3528 and 3780 is 252
</pre>
 
 
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)</langsyntaxhighlight>
 
Using pattern matching
 
<langsyntaxhighlight lang="scala">@tailrec
def gcd(a: Int, b: Int): Int = {
b match {
Line 4,809 ⟶ 6,100:
case _ => gcd(b, (a % b))
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (gcd a b)
(if (= b 0)
a
(gcd b (modulo a b))))</langsyntaxhighlight>
 
or using the standard function included with Scheme (takes any number of arguments):
<syntaxhighlight lang ="scheme">(gcd a b)</langsyntaxhighlight>
 
=={{header|Sed}}==
 
<langsyntaxhighlight lang="sed">#! /bin/sed -nf
 
# gcd.sed Copyright (c) 2010 by Paweł Zuzelski <pawelz@pld-linux.org>
Line 5,131 ⟶ 6,422:
b next
 
# END OF GSU dc.sed</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const func integer: gcd (in var integer: a, in var integer: b) is func
result
var integer: gcd is 0;
Line 5,146 ⟶ 6,437:
end while;
gcd := b;
end func;</langsyntaxhighlight>
Original source: [http://seed7.sourceforge.net/algorith/math.htm#gcd]
 
=={{header|SequenceL}}==
Tail Recursive Greatest Common Denominator using Euclidian Algorithm
<langsyntaxhighlight lang="sequencel">gcd(a, b) :=
a when b = 0
else
gcd(b, a mod b);</langsyntaxhighlight>
 
=={{header|SETL}}==
<langsyntaxhighlight lang="setl">a := 33; b := 77;
print(" the gcd of",a," and ",b," is ",gcd(a,b));
 
Line 5,165 ⟶ 6,456:
proc gcd (u, v);
return if v = 0 then abs u else gcd (v, u mod v) end;
end;</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight lang="setl">the gcd of 33 and 77 is 11
the gcd of 49865 and 69811 is 9973</langsyntaxhighlight>
 
=={{header|Sidef}}==
===Built-in===
 
<langsyntaxhighlight lang="ruby">var arr = [100, 1_000, 10_000, 20];
say Math.gcd(arr...);</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
 
<langsyntaxhighlight lang="ruby">func gcd(a, b) {
b.is_zero ? a.abs : gcd(b, a % b);
}</langsyntaxhighlight>
 
=={{header|Simula}}==
For a recursive variant, see [[Sum multiples of 3 and 5#Simula|Sum multiples of 3 and 5]].
<langsyntaxhighlight lang="algolw">BEGIN
INTEGER PROCEDURE GCD(a, b); INTEGER a, b;
BEGIN
Line 5,207 ⟶ 6,498:
OUTIMAGE
END
END</langsyntaxhighlight>
{{out}}
<pre>(0, 1) 1 (2, 1) 1 (4, 1) 1 (6, 1) 1 (8, 1) 1 (10, 1) 1 (12, 1) 1 (14, 1) 1 (16, 1) 1 (18, 1) 1 (20, 1) 1
Line 5,223 ⟶ 6,514:
Slate's Integer type has gcd defined:
 
<syntaxhighlight lang ="slate">40902 gcd: 24140</langsyntaxhighlight>
 
===Iterative Euclid algorithm===
 
<langsyntaxhighlight lang="slate">x@(Integer traits) gcd: y@(Integer traits)
"Euclid's algorithm for finding the greatest common divisor."
[| n m temp |
Line 5,234 ⟶ 6,525:
[n isZero] whileFalse: [temp: n. n: m \\ temp. m: temp].
m abs
].</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="slate">x@(Integer traits) gcd: y@(Integer traits)
[
y isZero
ifTrue: [x]
ifFalse: [y gcd: x \\ y]
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
The <tt>Integer</tt> class has its <tt>gcd</tt> method.
 
<syntaxhighlight lang ="smalltalk">(40902 gcd: 24140) displayNl</langsyntaxhighlight>
 
An reimplementation of the Iterative Euclid's algorithm would be:
 
<langsyntaxhighlight lang="smalltalk">|gcd_iter|
 
gcd_iter := [ :a :b |
Line 5,265 ⟶ 6,556:
].
 
(gcd_iter value: 40902 value: 24140) printNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol"> define('gcd(i,j)') :(gcd_end)
gcd ?eq(i,0) :s(freturn)
?eq(j,0) :s(freturn)
Line 5,279 ⟶ 6,570:
 
output = gcd(1071,1029)
end</langsyntaxhighlight>
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">function factors(n) {
var f = {};
 
Line 5,314 ⟶ 6,605:
function LCM(n, k) {
return n * k / GCD(n, k);
}</langsyntaxhighlight>
 
=={{header|SQL}}==
Demonstration of Oracle 12c WITH Clause Enhancements
<langsyntaxhighlight SQLlang="sql">drop table tbl;
create table tbl
(
Line 5,352 ⟶ 6,643:
from tbl
/
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,389 ⟶ 6,680:
 
Demonstration of SQL Server 2008
<langsyntaxhighlight SQLlang="sql">CREATE FUNCTION gcd (
@ui INT,
@vi INT
Line 5,432 ⟶ 6,723:
 
DROP FUNCTION gcd;
</syntaxhighlight>
</lang>
 
PostgreSQL function using a recursive common table expression
<langsyntaxhighlight SQLlang="sql">CREATE FUNCTION gcd(integer, integer)
RETURNS integer
LANGUAGE sql
Line 5,446 ⟶ 6,737:
SELECT min(u) FROM x;
$function$
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,457 ⟶ 6,748:
Time: 0.012s
</pre>
 
=={{header|Standard ML}}==
 
See also [[#ML / Standard ML]].
 
<syntaxhighlight lang="sml">(* Euclid’s algorithm. *)
 
fun gcd (u, v) =
let
fun loop (u, v) =
if v = 0 then
u
else
loop (v, u mod v)
in
loop (abs u, abs v)
end
 
(* Using the Rosetta Code example for assertions in Standard ML. *)
fun assert cond =
if cond then () else raise Fail "assert"
val () = assert (gcd (0, 0) = 0)
val () = assert (gcd (0, 10) = 10)
val () = assert (gcd (~10, 0) = 10)
val () = assert (gcd (9, 6) = 3)
val () = assert (gcd (~6, ~9) = 3)
val () = assert (gcd (40902, 24140) = 34)
val () = assert (gcd (40902, ~24140) = 34)
val () = assert (gcd (~40902, 24140) = 34)
val () = assert (gcd (~40902, ~24140) = 34)
val () = assert (gcd (24140, 40902) = 34)
val () = assert (gcd (~24140, 40902) = 34)
val () = assert (gcd (24140, ~40902) = 34)
val () = assert (gcd (~24140, ~40902) = 34)</syntaxhighlight>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function gcd(a_,b_) {
a = abs(a_)
b = abs(b_)
Line 5,468 ⟶ 6,794:
}
return(a)
}</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">// Iterative
 
func gcd(var a: Int, var b: Int) -> Int {
var a = abs(a); b = abs(b)
var b = abs(b)
if (b > a) { swap(&a, &b) }
Line 5,486 ⟶ 6,813:
// Recursive
 
func gcdr (var a: Int, var b: Int) -> Int {
var a = abs(a); b = abs(b)
var b = abs(b)
 
if (b > a) { swap(&a, &b) }
Line 5,506 ⟶ 6,834:
println("Iterative: GCD of \(a) and \(b) is \(gcd(a, b))")
println("Recursive: GCD of \(a) and \(b) is \(gcdr(a, b))")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,525 ⟶ 6,853:
=={{header|Tcl}}==
===Iterative Euclid algorithm===
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
proc gcd_iter {p q} {
Line 5,532 ⟶ 6,860:
}
abs $p
}</langsyntaxhighlight>
 
===Recursive Euclid algorithm===
<langsyntaxhighlight lang="tcl">proc gcd {p q} {
if {$q == 0} {
return $p
}
gcd $q [expr {$p % $q}]
}</langsyntaxhighlight>
With Tcl 8.6, this can be optimized slightly to:
<langsyntaxhighlight lang="tcl">proc gcd {p q} {
if {$q == 0} {
return $p
}
tailcall gcd $q [expr {$p % $q}]
}</langsyntaxhighlight>
(Tcl does not perform automatic tail-call optimization introduction because that makes any potential error traces less informative.)
 
===Iterative binary algorithm===
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}
proc gcd_bin {p q} {
Line 5,572 ⟶ 6,900:
}
return [* $p $k]
}</langsyntaxhighlight>
 
===Notes on performance===
<langsyntaxhighlight lang="tcl">foreach proc {gcd_iter gcd gcd_bin} {
puts [format "%-8s - %s" $proc [time {$proc $u $v} 100000]]
}</langsyntaxhighlight>
Outputs:
<pre>gcd_iter - 4.46712 microseconds per iteration
gcd - 5.73969 microseconds per iteration
gcd_bin - 9.25613 microseconds per iteration</pre>
 
=={{header|TI-83 BASIC}}, {{header|TI-89 BASIC}}==
gcd(A,B)
The ) can be omitted in TI-83 basic
 
=={{header|Tiny BASIC}}==
<lang Tiny BASIC>10 PRINT "First number"
20 INPUT A
30 PRINT "Second number"
40 INPUT B
50 IF A<0 THEN LET A=-A
60 IF B<0 THEN LET B=-B
70 IF A>B THEN GOTO 130
80 LET B = B - A
90 IF A=0 THEN GOTO 110
100 GOTO 50
110 PRINT B
120 END
130 LET C=A
140 LET A=B
150 LET B=C
160 GOTO 70</lang>
 
 
=={{header|Transact-SQL}}==
<syntaxhighlight lang="transact-sql">
<lang Transact-SQL>
CREATE OR ALTER FUNCTION [dbo].[PGCD]
( @a BigInt
Line 5,649 ⟶ 6,954:
 
END
</syntaxhighlight>
</lang>
 
 
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<lang basic>
REM Solución iterativa
FUNCTION gcdI(x, y)
DO WHILE y > 0
LET t = y
LET y = remainder(x, y)
LET x = t
LOOP
LET gcdI = x
END FUNCTION
 
 
LET a = 111111111111111
LET b = 11111
 
PRINT
PRINT "GCD(";a;", ";b;") = "; gcdI(a, b)
PRINT
PRINT "GCD(";a;", 111) = "; gcdI(a, 111)
END
</lang>
 
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tse sal">
<lang TSE SAL>
 
// library: math: get: greatest: common: divisor <description>greatest common divisor whole numbers. Euclid's algorithm. Recursive version</description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmacdi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 14:22:41]
Line 5,703 ⟶ 6,982:
END
 
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="bash">$ txr -p '(gcd (expt 2 123) (expt 6 49))'
562949953421312</langsyntaxhighlight>
 
=={{header|TypeScript}}==
Iterative implementation
<langsyntaxhighlight lang="javascript">function gcd(a: number, b: number) {
a = Math.abs(a);
b = Math.abs(b);
Line 5,728 ⟶ 7,007:
if (b === 0) { return a; }
}
}</langsyntaxhighlight>
 
Recursive.
<langsyntaxhighlight lang="javascript">function gcd_rec(a: number, b: number) {
return b ? gcd_rec(b, a % b) : Math.abs(a);
}</langsyntaxhighlight>
 
== [[:Category:Uiua|Uiua]] ==
=={{header|uBasic/4tH}}==
<syntaxhighlight>
{{trans|BBC BASIC}}
⊙◌⍢(⊃∘◿:)(±,)
<lang>Print "GCD of 18 : 12 = "; FUNC(_GCD_Iterative_Euclid(18,12))
</syntaxhighlight>
Print "GCD of 1071 : 1029 = "; FUNC(_GCD_Iterative_Euclid(1071,1029))
Print "GCD of 3528 : 3780 = "; FUNC(_GCD_Iterative_Euclid(3528,3780))
 
End
 
_GCD_Iterative_Euclid Param(2)
Local (1)
Do While b@
c@ = a@
a@ = b@
b@ = c@ % b@
Loop
Return (Abs(a@))</lang>
{{out}}
<pre>GCD of 18 : 12 = 6
GCD of 1071 : 1029 = 21
GCD of 3528 : 3780 = 252
 
0 OK, 0:205</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">gcd() {
# Calculate $1 % $2 until $2 becomes zero.
until test 0 -eq "$2"; do
Line 5,773 ⟶ 7,034:
 
gcd -47376 87843
# => 987</langsyntaxhighlight>
 
==={{header|dash or bash}}===
Procedural :
<langsyntaxhighlight lang="bash">gcd() { until test 0 -eq "$2";do set -- "$2" "$(($1 % $2))";done;if [ 0 -gt "$1" ];then echo "$((- $1))";else echo "$1"; fi }
 
gcd -47376 87843
# => 987</langsyntaxhighlight>
 
 
Recursive :
<langsyntaxhighlight lang="bash">
gcd () { if [ "$2" -ne 0 ];then gcd "$2" "$(($1 % $2))";else echo "$1";fi }
 
gcd 100 75
# => 25</langsyntaxhighlight>
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">alias gcd eval \''set gcd_args=( \!*:q ) \\
@ gcd_u=$gcd_args[2] \\
@ gcd_v=$gcd_args[3] \\
Line 5,805 ⟶ 7,066:
gcd result -47376 87843
echo $result
# => 987</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">import "math"
out (gcd 40902 24140) endl console</langsyntaxhighlight>
{{out}}
<pre>34</pre>
Line 5,819 ⟶ 7,080:
it includes a bit shifting optimization that happens when both operands
are even.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
gcd = ~&B?\~&Y ~&alh^?\~&arh2faltPrXPRNfabt2RCQ @a ~&ar^?\~&al ^|R/~& ^/~&r remainder</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nWnAL
 
test = ^(~&,gcd)* <(25,15),(36,16),(120,45),(30,100)></langsyntaxhighlight>
output:
<pre><
Line 5,861 ⟶ 7,122:
|1071 1029 gcd
=21
 
=={{header|VBA}}==
<lang vb>Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function</lang>
This function uses repeated subtractions. Simple but not very efficient.
<lang VBA>Public Function GCD(a As Long, b As Long) As Long
While a <> b
If a > b Then a = a - b Else b = b - a
Wend
GCD = a
End Function</lang>{{out}}
Example:
<pre>print GCD(1280, 240)
80
print GCD(3475689, 23566319)
7
a=123456789
b=234736437
print GCD((a),(b))
3 </pre>
 
A note on the last example: using brackets forces a and b to be evaluated before GCD is called. Not doing this will cause a compile error because a and b are not the same type as in the function declaration (they are Variant, not Long). Alternatively you can use the conversion function CLng as in print GCD(CLng(a),CLng(b))
 
=={{header|VBScript}}==
<lang VBScript>Function GCD(a,b)
Do
If a Mod b > 0 Then
c = a Mod b
a = b
b = c
Else
GCD = b
Exit Do
End If
Loop
End Function
 
WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,23566319) & "."
WScript.Echo "The GCD of 1280 and 240 is " & GCD(123456789,234736437) & "."</lang>
 
{{Output}}
<pre>The GCD of 48 and 18 is 6.
The GCD of 1280 and 240 is 80.
The GCD of 1280 and 240 is 7.
The GCD of 1280 and 240 is 3.</pre>
 
=={{header|Verilog}}==
<langsyntaxhighlight Veriloglang="verilog">module gcd
(
input reset_l,
Line 5,962 ⟶ 7,169:
 
endmodule
</syntaxhighlight>
</lang>
 
=={{header|VisualV Basic(Vlang)}}==
===Iterative===
{{works with|Visual Basic|5}}
<syntaxhighlight lang="go">fn gcd(xx int, yy int) int {
{{works with|Visual Basic|6}}
mut x, mut y := xx, yy
{{works with|VBA|6.5}}
for y != 0 {
{{works with|VBA|7.1}}
x, y = y, x%y
<lang vb>Function GCD(ByVal a As Long, ByVal b As Long) As Long
Dim h As Long }
return x
 
}
If a Then
If b Then
fn main() {
Do
println(gcd(33, 77))
h = a Mod b
println(gcd(49865, 69811))
a = b
}
b = h
</syntaxhighlight>
Loop While b
===Builtin===
End If
(This is just a wrapper for <tt>big.gcd</tt>)
GCD = Abs(a)
<syntaxhighlight lang="v (vlang)">import math.big
Else
fn gcd(x i64, y i64) i64 {
GCD = Abs(b)
return big.integer_from_i64(x).gcd(big.integer_from_i64(y)).int()
End If
}
End Function
fn main() {
 
println(gcd(33, 77))
Sub Main()
println(gcd(49865, 69811))
' testing the above function
}</syntaxhighlight>
 
{{out|Output in either case}}
Debug.Assert GCD(12, 18) = 6
<pre>
Debug.Assert GCD(1280, 240) = 80
11
Debug.Assert GCD(240, 1280) = 80
9973
Debug.Assert GCD(-240, 1280) = 80
</pre>
Debug.Assert GCD(240, -1280) = 80
Debug.Assert GCD(0, 0) = 0
Debug.Assert GCD(0, 1) = 1
Debug.Assert GCD(1, 0) = 1
Debug.Assert GCD(3475689, 23566319) = 7
Debug.Assert GCD(123456789, 234736437) = 3
Debug.Assert GCD(3780, 3528) = 252
End Sub</lang>
 
=={{header|Wortel}}==
Operator
<syntaxhighlight lang ="wortel">@gcd a b</langsyntaxhighlight>
Number expression
<syntaxhighlight lang ="wortel">!#~kg a b</langsyntaxhighlight>
Iterative
<langsyntaxhighlight lang="wortel">&[a b] [@vars[t] @while b @:{t b b %a b a t} a]</langsyntaxhighlight>
Recursive
<langsyntaxhighlight lang="wortel">&{gcd a b} ?{b !!gcd b %a b @abs a}</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var gcd = Fn.new { |x, y|
while (y != 0) {
var t = y
Line 6,021 ⟶ 7,220:
x = t
}
return x.abs
}
 
System.print("gcd(33, 77) = %(gcd.call(33, 77))")
System.print("gcd(49865, 69811) = %(gcd.call(49865, 69811))")</langsyntaxhighlight>
 
{{out}}
Line 6,035 ⟶ 7,234:
=={{header|x86 Assembly}}==
Using GNU Assembler syntax:
<langsyntaxhighlight lang="8086 Assemblyassembly">.text
.global pgcd
 
Line 6,058 ⟶ 7,257:
pop %edx
leave
ret</langsyntaxhighlight>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<lang xbasic>
PROGRAM "gcddemo"
VERSION "0.001"
 
DECLARE FUNCTION Entry()
DECLARE FUNCTION GcdRecursive(u&, v&)
DECLARE FUNCTION GcdIterative(u&, v&)
DECLARE FUNCTION GcdBinary(u&, v&)
 
FUNCTION Entry()
m& = 49865
n& = 69811
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdIterative(m&, n&); " (iterative)"
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdRecursive(m&, n&); " (recursive)"
PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdBinary (m&, n&); " (binary)"
END FUNCTION
 
FUNCTION GcdRecursive(u&, v&)
IF u& MOD v& <> 0 THEN
RETURN GcdRecursive(v&, u& MOD v&)
ELSE
RETURN v&
END IF
END FUNCTION
 
FUNCTION GcdIterative(u&, v&)
DO WHILE v& <> 0
t& = u&
u& = v&
v& = t& MOD v&
LOOP
RETURN ABS(u&)
END FUNCTION
 
FUNCTION GcdBinary(u&, v&)
u& = ABS(u&)
v& = ABS(v&)
IF u& < v& THEN
t& = u&
u& = v&
v& = t&
END IF
IF v& = 0 THEN
RETURN u&
ELSE
k& = 1
DO WHILE (u& MOD 2 = 0) && (v& MOD 2 = 0)
u& = u& >> 1
v& = v& >> 1
k& = k& << 1
LOOP
IF u& MOD 2 = 0 THEN
t& = u&
ELSE
t& = -v&
END IF
DO WHILE t& <> 0
DO WHILE t& MOD 2 = 0
t& = t& \ 2
LOOP
IF t& > 0 THEN
u& = t&
ELSE
v& = -t&
END IF
t& = u& - v&
LOOP
RETURN u& * k&
END IF
END FUNCTION
 
END PROGRAM
</lang>
{{out}}
<pre>
GCD(49865, 69811): 9973 (iterative)
GCD(49865, 69811): 9973 (recursive)
GCD(49865, 69811): 9973 (binary)
</pre>
 
=={{header|XLISP}}==
<code>GCD</code> is a built-in function. If we wanted to reimplement it, one (tail-recursive) way would be like this:
<langsyntaxhighlight lang="lisp">(defun greatest-common-divisor (x y)
(if (= y 0)
x
(greatest-common-divisor y (mod x y)) ) )</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
func GCD(U, V); \Return the greatest common divisor of U and V
Line 6,161 ⟶ 7,278:
 
\Display the GCD of two integers entered on command line
IntOut(0, GCD(IntIn(8), IntIn(8)))</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<lang Yabasic>sub gcd(u, v)
local t
u = int(abs(u))
v = int(abs(v))
while(v)
t = u
u = v
v = mod(t, v)
wend
return u
end sub
 
print "Greatest common divisor: ", gcd(12345, 9876)</lang>
 
=={{header|Z80 Assembly}}==
Uses the iterative subtraction implementation of Euclid's algorithm because the Z80 does not implement modulus or division opcodes.
<langsyntaxhighlight lang="z80">; Inputs: a, b
; Outputs: a = gcd(a, b)
; Destroys: c
Line 6,202 ⟶ 7,303:
ld a, c
 
jr gcd</langsyntaxhighlight>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">pub fn gcd(u: anytype, v: anytype) @TypeOf(u) {
if (@typeInfo(@TypeOf(u)) != .Int) {
@compileError("non-integer type used on gcd: " ++ @typeName(@TypeOf(u)));
}
if (@typeInfo(@TypeOf(v)) != .Int) {
@compileError("non-integer type used on gcd: " ++ @typeName(@TypeOf(v)));
}
return if (v != 0) gcd(v, @mod(u,v)) else u;
}</syntaxhighlight>
 
=={{header|zkl}}==
This is a method on integers:
<langsyntaxhighlight lang="zkl">(123456789).gcd(987654321) //-->9</langsyntaxhighlight>
Using the gnu big num library (GMP):
<langsyntaxhighlight lang="zkl">var BN=Import("zklBigNum");
BN(123456789).gcd(987654321) //-->9</langsyntaxhighlight>
or
<langsyntaxhighlight lang="zkl">fcn gcd(a,b){ while(b){ t:=a; a=b; b=t%b } a.abs() }</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 FOR n=1 TO 3
20 READ a,b
30 PRINT "GCD of ";a;" and ";b;" = ";
40 GO SUB 70
50 NEXT n
60 STOP
70 IF b=0 THEN PRINT ABS (a): RETURN
80 LET c=a: LET a=b: LET b=FN m(c,b): GO TO 70
90 DEF FN m(a,b)=a-INT (a/b)*b
100 DATA 12,16,22,33,45,67</lang>
55

edits