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
fsharp
let rec gcd x y =
if y = 0 then x
else gcd y (x % y)
ExpandDiskEdit
fantom
gcd := |Int a, Int b -> Int| {
pair := [a, b].sort
while (pair.first != 0)
pair.set(1, pair.last % pair.first).swap(0, 1)
return pair.last
}
echo(gcd(12, 8)) // a>b, result == 4
echo(gcd(1029, 1071)) // a<b, result == 21
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))
}

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