Saturday, November 14, 2009

Greatest Common Divisor and Least Common Multiple functions in Haskell

Recently, I wrote a post about finding the gcd and lcm with C: http://knowledge-aholic.blogspot.com/2009/11/greatest-common-divisor-and-least.html

Since then, I have started Haskell and here is how implemented the "same" functions with Haskell (note that with Haskell, I have to use recursion to find the gcd) :


mygcd :: Int -> Int -> Int
mygcd n m
 | m == 0 = n
 | otherwise = mygcd m (mod n m)
 
mylcm :: Int -> Int -> Int
mylcm n m = div (n * m) (mygcd n m)