Jump to content

Euclidean algorithm

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Zundark (talk | contribs) at 13:04, 8 January 2002 (factored out from Greatest_common_divisor). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

The Euclidean algorithm (also called Euclid's algorithm) is an extremely fast algorithm to determine the greatest common divisor (GCD) of two integers.

It was already contained in Euclid's Elements.

The algorithm does not require factoring.


Given two non-negative integers a and b, first check if b is zero. If yes, then the GCD is a. If no, calculate c, the remainder after the division of a by b. Replace a with b, b with c, and start the process again.


For example, the GCD of 1029 and 42 is computed by this algorithm to be 21 with the following steps:


a      b

102942
4221
210


For a more involved example, 46406 and 36957 can be seen to be relatively prime by the following computation:


a            b

4640636957
369579449
94498610
8610839
839220
220179
17941
4115
1511
114
43
31
10


By keeping track of the quotients occurring during the algorithm, one can also determine integers p and q with ap+bq = gcd(a,b). This is known as the extended Euclid's algorithm. Here is a Javascript implementation which should work in most browsers:



// This program works only for non-negative inputs.

// Get data from user and convert strings to integers.

var a = parseInt(prompt("Enter non-negative value for a",0))

var b = parseInt(prompt("Enter non-negative value for b",0))



// Save original values.

a0 = a;

b0 = b;



// Initializations. We maintain the invariant p*a0 + q*b0 = a and r*a0 + s*b0 = b.

p = 1; q = 0;

r = 0; s = 1;



// The algorithm:

while (b != 0) { 

  c = a % b;

  quot = Math.floor(a/b);  //Javascript doesn't have an integer division operator

  a = b;

  b = c;

  new_r = p - quot * r; new_s = q - quot * s;

  p = r; q = s;

  r = new_r; s = new_s;

}



// Show result.

alert("gcd(" + a0 + "," + b0 + ")=" + a + "\n" + p + "*" + a0 + "+(" + q + ")*" + b0 + "=" + a)


When analyzing the runtime of this version of Euclid's algorithm, it turns out that the inputs requiring the most steps are two successive Fibonacci numbers, and the worst case requires O(n) divisions, where n is the number of digits in the input (see Big O).


Euclid originally formulated the problem geometrically, as the problem of finding a common "measure" for two line lengths, and his algorithm proceeded by repeated subtraction of the shorter from the longer segment. This is illustrated with the following implementation in Python:



def gcd(a,b):

    while 1:

        if a == b:

            return a

        elif a > b:

            a = a - b

        else:

            b = b - a