Skip to content

Commit 12794b3

Browse files
committed
FEAT: new gcd native for resolving the greatest common divisor of two integers
1 parent 66739b9 commit 12794b3

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/core/n-math.c

+22
Original file line numberDiff line numberDiff line change
@@ -927,3 +927,25 @@ enum {SINE, COSINE, TANGENT};
927927

928928
return R_FALSE;
929929
}
930+
931+
/***********************************************************************
932+
**
933+
*/ REBNATIVE(gcd)
934+
/*
935+
// gcd: native [
936+
// {Returns greatest common divisor}
937+
// a [integer!]
938+
// b [integer!]
939+
// ]
940+
***********************************************************************/
941+
{
942+
REBINT a = VAL_INT64(D_ARG(1));
943+
REBINT b = VAL_INT64(D_ARG(2));
944+
945+
// Euclid's algorithm
946+
if (a < 0) a = -a;
947+
if (b < 0) b = -b;
948+
if (b) while ((a %= b) && (b %= a));
949+
SET_INTEGER(D_RET, a + b);
950+
return R_RET;
951+
}

src/tests/units/integer-test.r3

+11
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@ Rebol [
6060

6161
===end-group===
6262

63+
64+
===start-group=== "gcd"
65+
--test-- "gcd"
66+
--assert 6 = gcd 54 24
67+
--assert 6 = gcd 24 54
68+
--assert 3 = gcd 0 3
69+
--assert 3 = gcd 3 0
70+
--assert 3 = gcd 21 -48
71+
===end-group===
72+
73+
6374
===start-group=== "multiply"
6475
--test-- "0 * 1"
6576
i: 0

0 commit comments

Comments
 (0)