Euclid's Algorithm in Python?

Bengt Richter bokr at oz.net
Mon Aug 8 03:03:44 CEST 2005


On 7 Aug 2005 17:31:02 -0700, "Jordan Rastrick" <jrastrick at student.usyd.edu.au> wrote:

>Good point. I suppose I'd only ever seen it implemented with the if
>test, but you're right, the plain while loop should work fine. Silly
>me.
>
>def gcd(a,b):
>     while b != 0:
>           a, b = b, a%b
>    return a
>
>Even nicer.
>
what is the convention for handling signed arguments? E.g.,

 >>> def gcd(a,b):
 ...     while b != 0:
 ...         a, b = b, a%b
 ...     return a
 ...
 >>> gcd(3, -12)
 -3
 >>> gcd(-12, 3)
 3

Regards,
Bengt Richter



More information about the Python-list mailing list