View Problem

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

DiskEdit
groovy
static def gcd(int i, int j) {
if (Math.min(i,j)==0) return Math.max(i,j)
else return gcd(Math.min(i,j),Math.abs(i-j))
}
DiskEdit
erlang
-module(gcd).
-export([gcd/2]).

gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).
DiskEdit
clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))

Submit a new solution for groovy, erlang, or clojure
There are 14 other solutions in additional languages (cpp, csharp, fantom, fsharp ...)