GCD in standard library?

Tim Peters tim.one at comcast.net
Wed Mar 12 21:17:01 EST 2003


[Blake Garretson]
> Unless I've been missing something for years, I don't believe
> there are any functions built-in or in the standard library that
> find the Greatest Common Divsor (GCD) of two integers.

That's so.

> This seems like a common enough math function that I would *think* it
> ought to be in the math module (and gain the advantage of being coded
> in C.)

What advantage would that be?  The speed of gcd on large integers is
dominated by the speed of large-integer arithmetic, and that's coded in C no
matter how it's *driven*.

> I guess I'm wondering why it isn't there.

Because it's trivial to code in (literally) a few lines of Python.

> Was it to keep out code bloat?  I realize we can't include everyone's pet
> function, so it's fine if it stays out.  I'm just guessing it is
> very common for people to have to add this to their programs:
>
> def gcd(x,y):
>   if x % y == 0: return y
>   else: return gcd(y,x%y)

Nope, I've never seen it written that way in Python.  This spelling is
common, in the relative handful of programs that want it:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

> ...
> If Python comes with "batteries included", where's GCD?

httplib and builtin unbounded ints are batteries; gcd is a throwaway finger
exercise in a Usenet posting.  BTW, I've never seen another user community
so keen to lobby for inclusion of every 1-, 2- and 3-line function they can
dream up.  Even Common Lisp had the good grace to restrict itself to
12-liners, like builtin Roman numeral output <wink>.






More information about the Python-list mailing list