Euclidean algorithm (Haskell)

From LiteratePrograms

Jump to: navigation, search
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 Haskell, using a function that recurses on the remainder of the division of a by b until that remainder is 0. Note that for practical purposes you should instead use the "gcd" function that is already provided in the Prelude, which also handles negative numbers and the case where both args are 0.

gcd a 0 = a
gcd a b = gcd b (a `mod` b)

Performing the Euclidean algorithm on an arbitrary list of integers is also relatively straight-forward using the above function. Note that 0 is an identity for gcd.

gcdList = foldl gcd 0
Download code
Views