Topics Register • News • History • How to • Sequences statistics • Template prototypes

Greatest common divisor

The Greatest common divisor (gcd) of two numbers, commonly expressed by $\displaystyle{ gcd(a, b) }$, where $\displaystyle{ a }$ and $\displaystyle{ b }$ are positive integers, is the maximum number that divides both $\displaystyle{ a }$ and $\displaystyle{ b }$.

We can also define $\displaystyle{ gcd(a, 0) = a }$ and $\displaystyle{ gcd(a, b) = gcd(|a|, |b|) }$ thus defining the operations for all integers.

When the greatest common divisor is 1, both numbers are coprime or relatively prime. This does not mean that either of these numbers are prime.

Although the GCD can be readily computed if the prime factors of both numbers are known, in the context of this wiki the numbers are not factored in advance and the GCD helps find a factor of these numbers, so an alternate method is required.

Fortunately Euclid discovered such an algorithm more than 2000 years ago. Expressed in modern notation the algorithm is:

1. If $\displaystyle{ b = 0 }$, terminate the algorithm with $\displaystyle{ a = 0 }$ as the answer.
2. Set a temporary variable $\displaystyle{ r }$ to $\displaystyle{ a\,\mathrm{mod}\,b }$.
3. Set the variable $\displaystyle{ a }$ to $\displaystyle{ b }$.
4. Set the variable $\displaystyle{ b }$ to $\displaystyle{ r }$.
5. Go back to step 1.

There are faster methods, especially when number of thousands or millions of digits are used, as in GIMPS, but they are much more complex than the one presented above.