Haskell Program to find the LCM of two given numbers using recursion


In Haskell, we will find the the LCM of two given numbers by using recursion along with gcd and max function. In the first example, we are going to use (gcd) and (lcmOfTwoNumbers) function and in the second example, we are going to use (lcm) and (lcmOfTwoNumbers a b = lcm a b (max a b)) function.

Algorithm

  • Step 1 − The Prelude library is imported for hiding the gcd function.

  • Step 2 − Define two user-defined functions - gcd and lcmOfTwoNumbers ,

  • Step 3 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. In the main function, the values of a and b are set to 15 and 20, respectively. The LCM of these two numbers is then calculated by calling lcmOfTwoNumbers a b, and the result is displayed to the console.

  • Step 4 − The variables named, “a” and “b” are being initialized. It will hold the numbers whose lcm is to be computed.

  • Step 5 − The resultant lcm of the given two numbers is printed to the console using ‘show’ function after the function is called.

Example 1

In this example, the LCM of two numbers a and b is found using the gcd function to calculate the greatest common divisor of the two numbers, and then uses this value to calculate the LCM.

import Prelude hiding (gcd)

gcd :: Int -> Int -> Int
gcd a 0 = a
gcd a b = gcd b (a `mod` b)

lcmOfTwoNumbers :: Int -> Int -> Int
lcmOfTwoNumbers a 0 = 0
lcmOfTwoNumbers a b = abs (a * (b `div` (gcd a b)))

main :: IO ()
main = do
   let a = 15
   let b = 20
   putStrLn $ "The LCM of " ++ show a ++ " and " ++ show b ++ " is: " ++ show (lcmOfTwoNumbers a b)

Output

The LCM of 15 and 20 is: 60

Example 2

In this example, the LCM of two numbers a and b is found using the max and mod function, and then printed it to the console.

import Prelude hiding (lcm)
lcm :: Int -> Int -> Int -> Int
lcm a b c
   | c `mod` a == 0 && c `mod` b == 0 = c
   | otherwise = lcm a b (c + 1)

lcmOfTwoNumbers :: Int -> Int -> Int
lcmOfTwoNumbers a b = lcm a b (max a b)

main :: IO ()
main = do
   let a = 15
   let b = 20
   putStrLn $ "The LCM of " ++ show a ++ " and " ++ show b ++ " is: " ++ show (lcmOfTwoNumbers a b)

Output

The LCM of 15 and 20 is: 60

Conclusion

In mathematics, the least common multiple (LCM) of two or more numbers is the smallest positive integer that is a multiple of all of them. In Haskell, the LCM of two or more numbers can be calculated using various mathematical algorithms and using recursion.

Updated on: 27-Mar-2023

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements