Euclid's Algorithm in Python?

Jordan Rastrick jrastrick at student.usyd.edu.au
Thu Aug 4 23:13:11 EDT 2005


Raising an assertion error for a < b is a bit of overkill, since its
not really a case of bad input. So normally you see Euclid done like
this:

def gcd(a,b): # All lowercase for a function is a bit more
conventional.
    if a < b:
         a, b = b, a # Ensures a >= b by swapping a and b if nessecary
    while b != 0: # Note parentheses are unnessecary here in python
         a, b = b, a % b
    return a

A bit more concise and no less readable (IMO).

If you really want to check for actual bad input, youre better off
testing, for example, than a and b are both greater than 0....

jepler at unpythonic.net wrote:
> Well, this article
> 	http://pythonjournal.cognizor.com/pyj1/AMKuchling_algorithms-V1.html
> was the first hit on google for '"euclid's algorithm" python'.
>
> It contains this function:
>     def GCD(a,b):
> 	assert a >= b     # a must be the larger number
> 	while (b != 0):
> 	    remainder = a % b
> 	    a, b  = b, remainder
> 	return a
> 
> Jeff




More information about the Python-list mailing list