Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!wuarchive!psuvax1!psuvm!cxt105 From: CXT105@psuvm.psu.edu (Christopher Tate) Newsgroups: comp.lang.postscript Subject: Re: GCD algorithm Message-ID: <90305.105824CXT105@psuvm.psu.edu> Date: 1 Nov 90 15:58:24 GMT Organization: Penn State University Lines: 83 Supersedes: <90305.103320CXT105@psuvm.psu.edu> In article <1990Oct31.182705.3184@light.uucp>, bvs@light.uucp (Bakul Shah) says: >- To justify posting this to a PostScript group, here is a faster > version of basically the same algorithm: > > /gcd { % given m, n on the stack > dup 3 1 roll mod % leaves n, m mod n on the stack > dup 0 eq { > pop % leaves n on the stack when done > } { > gcd % find gcd of the new pair > } ifelse > } bind def > > Not too surprisingly, this recursive version is faster than > the one below which uses an explicit loop: > > /gcd { > { dup 3 1 roll mod dup 0 eq { pop exit } if } loop > } bind def > > [stuff deleted] > > So.... Who is right? How did two different alg. came to be > known as Euclid's? Does the faster alg. also have such a nice > generalization for gcd of N numbers? The slower alg. can be > modified slightly to simulteneously compute LCM. Can the same > thing be done with the faster one? Time to visit a library! As it happens, I'm takinga computational number theory course even as we speak :-), so here's what my text has to say on the subject of Euclid's GCD algorithm.... Essentially, the whole thing works because of this odd property of the GCD; namely, that gcd(a, b) = m*a + n*b for some integers m and n (not necessarily unique). From this, we can do some fiddling with the properties of division and so on to show that gcd(a, b) = gcd(b, a - m*b) for ANY integer m. In Euclid's algorithm, we essentially take m to be as large as possible, i.e. a - m*b is as close to zero as possible. Since we can write r = a mod b = a - m*b (for m as large as possible), we simply use a mod b for the next iteration, and try to calculate gcd(b, a mod b). I once ran across a version of this algorithm (in C) which looked like this: int gcd(int a, int b) { if (a>b) return gcd(a, a-b); else if (a