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
python python 2.7
def gcd_recursive(i, j):
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))

def gcd_iterative(i, j):
while min(i, j) != 0:
i, j = min(i, j), abs(i - j)
return max(i, j)

if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
DiskEdit
python 2.6+
from fractions import gcd
print gcd(8, 12)
DiskEdit
clojure
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod b a))))
ExpandDiskEdit
csharp
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
DiskEdit
erlang
-module(gcd).
-export([gcd/2]).

gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem B).

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