Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

Euclid's algorithm for the greatest common divisor in Java

Lars Vogel

Version 0.1

25.05.2009

Revision History
Revision 0.117.05.2009Lars Vogel
Created

Euclid's GCD

This article describes how to calculate in Java the greatest common divisor of two positive number with Euclid's algorithm.


Table of Contents

1. Euclid's Algorithm the the greatest common divisor
2. Implementation in Java
3. Thank you
4. Questions and Discussion
5. Links and Literature
5.1. Source Code
5.2. General

1. Euclid's Algorithm the the greatest common divisor

The greatest common divisor (gcd) of two positive integers is the largest integer that divides both without remainder.

Euclid's algorithm is based on the following property: if p>q then the gcd of p and q is the same as the gcd of p%q and q.

p%q is the remainder of p which cannot be divided by q, e.g. 33 % 5 is 3.

This is based on the fact that the gcd of p and q also must divided (p-q) or (p-2q) or (p-3q). Therefore you can subtract the maximum of a multitude q from p which is p%q.