# Euclidean algorithm (Java)

### From LiteratePrograms

**Other implementations**: C | Erlang | Forth | Haskell |**Java**| Java, recursive | OCaml | Prolog | Python | Scala | Standard ML

The Java implementation of the Euclidean algorithm is remarkably similar to the C implementation of the Euclidean algorithm.

<<Euclidean algorithm loop>>=while(b != 0){intm = a % b; a = b; b = m;}returna;

We only need to ensure that *a* > *b* by swapping the inputs at the start of the function, if necessary:

<<Euclidean algorithm>>=publicstaticintgcd(inta,intb){if(b > a){inttemp = a; a = b; b = temp;}Euclidean algorithm loop}

Download code |