# Haskell Program to find the LCM using library function

In Haskell, we can use GCD function to find the LCM of the given number. In the first example we are going to use (a * b) div (gcd a b) function and in the second example, we are going to use foldl' (\x y -> (x*y) div (gcd x y)) function. In third example, we are going to use gcd' b (a mod b) function.

### Algorithm

• Step 1 − The lcm function is defined using gcd function as, lcm a b = (a * b) div (gcd a b).

• Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. It calls the lcm function with the values and prints the lcm of the two.

• Step 3 − The variables named, “a” and “b” are being initialized. It will hold the value to find the lcm of both.

• Step 4 − The resultant lcm value is printed to the console using ‘putStrLn’ statement after the function is called.

### Example 1

In this example, we are going to see that how we can find the lcm of given numbers. This can be done by using gcd function.

import Prelude

lcm :: Integral a => a -> a -> a
lcm a b = (a * b) div (gcd a b)

main :: IO ()
main = do
let a = 4
let b = 5
let lcmVal = Prelude.lcm a b


### Output

The LCM of 4 and 5 is: 20


### Example 3

In this example, we are going to see that how we can find the lcm of given numbers. This can be done by using gcd function and foldl1 function. This example uses the foldl1 function which uses the first element of the list as the initial accumulator value, to iterate through a list of integers, and calculates the LCM of the elements in the list.

import Data.List (foldl1')

lcm''' :: Integral a => [a] -> a
lcm''' = foldl1' (\x y -> (x*y) div (gcd x y))

main :: IO ()
main = do
let a = 4
let b = 5
let lcmVal = Prelude.lcm a b


### Output

The LCM of 4 and 5 is: 20


## Conclusion

In Haskell, there is no built-in function in the Prelude library to find the LCM of two numbers, but we can use the gcd function from the Prelude library to find the GCD of two numbers and then use that to find the LCM. To find the lcm of the given numbers, we can use the gcd functions along with foldl or foldl1 functions in Haskell. It can also be obtained using gcd function recursively.

Updated on: 13-Mar-2023

59 Views