GCD in standard library?
Steven Taschuk
staschuk at telusplanet.net
Wed Mar 12 22:08:18 EST 2003
Quoth Blake Garretson:
> [...] 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)
I for one haven't needed this in Python yet, but if I did I'd do
it this way:
def gcd(a, b):
while b:
a, b = b, a % b
return abs(a)
which (1) avoids the unnecessary recursion, (2) gives the right
answer for zero operands, and (3) gives a predictable and
defensible, if not obviously right, answer for negative operands.
I don't know why it's not in the standard library as you inquire;
one reason may be simply that it's not in the standard C math
library.
--
Steven Taschuk staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
-- Tony Dylan Davis (CKUA)
More information about the Python-list
mailing list