Euclid algorithm for Greatest common Denominator, SML
January 28, 2013 Leave a comment
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.