# Euclidean algorithm (Java, recursive)

From LiteratePrograms

**Other implementations**: C | Erlang | Haskell | Java |**Java, recursive**| 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*

This article describes a recursive Java implementation of the algorithm.

The *gcd* method requires that *a* and *b* are positive integers and that *a* > *b*.

<<gcd method>>=publicstaticlonggcd(longa,longb){base case general case}

The base case applies when *b* is equal to 0:

<<base case>>=if(b == 0)returna;

Since *a* > *b*, the first identity can be used for the general case:

<<general case>>=elsereturngcd(b, a % b);

## [edit] Sample code and demonstration

Here's some code demonstrating how to use the above method:

<<Euclid.java>>=publicclassEuclid{gcd methodpublicstaticvoidmain(String[]args){longn0 = Long.parseLong(args[0]);longn1 = Long.parseLong(args[1]);longres;if(n0 > n1)res = gcd(n0, n1);elseif(n1 > n0)res = gcd(n1, n0);elseres = n0; System.out.println(res);}}

If we compile and run the following command lines:

java Euclid 35 42 java Euclid 35 40 java Euclid 35 38

We get the following outputs:

7 5 1

Download code |