Euclid algorithm for Greatest common Denominator, SML

fun gcd (x,y) = 
    if y = 0 then x 
    else gcd(y, x mod y)

I’ve wondered how to easily do this in code, without having to brute force it.  Turns out Euclid worked out the algorithm over 2,000 years ago.

Even if you aren’t a programmer, you can probably follow this code if you understand that “x mod y” gives you the remainder of x divided by y.  Then you need to understand recursion, but you’ll need to understand recursion first.

I don’t recall ever learning this technique in school.  It would have made some operations on fractions easier.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s