Euclidean algorithm (Erlang)
From LiteratePrograms
- Other implementations: C | Erlang | Forth | Haskell | Java | Java, recursive | OCaml | Prolog | Python | Scala | Standard ML
The Euclidean algorithm is an efficient method for computing the greatest common divisor of two natural numbers (or polynomials, or any other object with the necessary structure), and was one of the first known algorithms to be described formally. It is based on the two identities:
- a > b implies: gcd(a, b) = gcd(b, a mod b)
- gcd(a, 0) = a
The Euclidean algorithm is straightforward to describe in Erlang, using a function that recurses on the remainder of the division of a by b until that remainder is 0.
gcd(A, 0) -> A; gcd(A, B) -> gcd(B, A rem B).
Performing the Euclidean algorithm on an arbitrary list of integers is also relatively straight-forward using the above function (denoted gcd/2 as Erlang functions are named by atom and arity).
gcd([H|T]) -> lists:foldl(fun gcd/2, H, T).
Download code |