[Tutor] Real LCM

Timothy M. Brauch tbrauch@mindless.com
Wed, 18 Jul 2001 21:03:43 -0400


Forgetting to send to the whole list the first time...


Danny Yoo presented us with, while talking about lcm(a,b): 
> Hmmm... I can't think of one that's built into the Python library.
> Neither is there a gcd() (greatest common divisor) function that's built
> in.  However, there's great algorithm by the mathematician Euclid called
> "Euclid's Algorithm" that calculates gcd's very quickly.  Really quickly:
> 
> ###
> def gcd(a, b):
>     if b == 0: return a
>     return gcd(b, a % b)
> ###
> 
> Euclid's algorithm is really useful, especially for rationalizing
> fractions.  Anyway, I did a quick lookup on google for the topic of "gcd's
> and lcm's", and got back this page:

Yes, I was already using this algorithm in my code for this project. 
One of the goals of this set of functions a sort of extension to the
current math module, and one that will work with a list with an
arbitrary length of numbers for functions that aren't in the math
module.

I am still struggling a little with the gcd for a complete list of
numbers, hopefully I will hack out a solution soon enough.  The mean,
median and mode was pretty simple.

Oh, and all these 'fun' projects I keep coming up with are mostly just
things I am coming up with to waste time.

> 
>     http://www.geocities.com/zabrodskyvlada/aat/a_eucl.html
> 
> The gcd() and lcm() are related: if we get the GCD of two numbers, getting
> their lcm() is really easy:
> 
>     "lcm(a, b) = a * b / gcd(a, b)"
> 
> The Python code for this reads very closely to the math.
> 
> Hope this helps!

This relationship of gcd and lcm is new to me.  It has helped with my
lists of two numbers.  As soon as I finish with the arbitrary length
gcd, I will try to implement the arbitrary length lcm.  Then, move on to
possibly new functions.

 - Tim