(Note that when computing gcd(a,b)
, we can assume that a <= b
; if that were not true, we could just swap them.)
The Euclidean algorithm is certainly the most efficient way to compute the gcd. But if you need two other (inefficient) ways to compute gcd(a,b)
, there are plenty:
-
Starting from
a
and going down, test every number to see if it divides botha
andb
. -
Prime-factorize
a
andb
(obtaining multisets of primes), and return the product of the intersection of these multisets. -
Find all divisors of
a
, and test if they divideb
starting froma
and going down. -
Find
lcm(a,b)
by testing which ofb, 2*b, 3*b, ...
is divisible bya
, and returna*b/(lcm(a,b))
.
1 and 4 are probably easiest to implement, since they don’t involve factoring.
It’s also important to note some edge cases: gcd(0,x) = x
for all x > 0
, while gcd(0,0)
is undefined. And technically I suppose gcd(a,b) = gcd(abs(a), abs(b))
covers the case where inputs may be negative.
2
solved Greatest common divisor algorithms OTHER than Euclid’s