Haskell Program to Display Factors of a Number


In Haskell, we can list comprehension, filter function and recursion to display factors of a number. In the first example we are going to use (factors n = [x | x <- [1..n], n `mod` x == 0]) as list comprehension and in the second example, we are going to use (filter (\x -> n `mod` x == 0) [1..n]) function. And in third example, we are going to use recursion with base and recursive case.

Algorithm

  • Step 1 − The user-defined factors function is defined using internal functions.

  • 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.

  • Step 3 − The variable named, “num” is being initialized. It will hold the number whose all factors are to be printed.

  • Step 4 − The resultant factors of the given number are printed to the console using ‘print’ function after the function is called.

Example 1

In this example, we are going to see that how we can display all the factors of a number by using list comprehension.

factors :: Integer -> [Integer]
factors n = [x | x <- [1..n], n `mod` x == 0]

main :: IO ()
main = do
   let num = 24
   print (factors num)

Output

[1,2,3,4,6,8,12,24]

Example 2

In this example, we are going to see that how we can display all the factors of a number by using filter function.

factors :: Integer -> [Integer]
factors n = filter (\x -> n `mod` x == 0) [1..n]

main :: IO ()
main = do
   let num = 24
   print (factors num)

Output

[1,2,3,4,6,8,12,24]

Example 3

In this example, we are going to see that how we can display all the factors of a number by using recursion.

factors :: Integer -> [Integer]
factors n = factors' n 1

factors' :: Integer -> Integer -> [Integer]
factors' n i
   | i > n = []
   | n `mod` i == 0 = i : factors' n (i+1)
   | otherwise = factors' n (i+1)

main :: IO ()
main = do
   let num = 24
   print (factors num)

Output

[1,2,3,4,6,8,12,24]

Conclusion

In Haskell, the factors of a number can be displayed to the console using list comprehension, filter function or recursion.

Updated on: 13-Mar-2023

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements