Haskell Program to Display Prime Numbers Between Two Intervals


In Haskell, we can display Prime Numbers between Two Intervals using user-defined functions and list comprehension. In the first example, we are going to use (isPrime and primesInRange) user-defined functions and in the second example, we are going to use list comprehension.

Algorithm

  • Step 1 − The Data.List library is imported.

  • Step 2 − The user-defined isPrime function is defined.

  • Step 3 − Program execution will be started from main function. The main() function has whole control of the program.

  • Step 4 − The variables named, “lower” and “upper” are being initialized. It will hold the range between which the prime numbers is to be printed.

  • Step 5 − The resultant prime numbers under the defined range is 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 prime numbers between two interval using user defined functions.

import Data.List (filter)

isPrime :: Integer -> Bool
isPrime n
   | n <= 1 = False
   | n == 2 = True
   | n `mod` 2 == 0 = False
   | otherwise = all (\x -> n `mod` x /= 0) [3,5..(floor (sqrt (fromIntegral n)))]

primesInRange :: Integer -> Integer -> [Integer]
primesInRange a b = filter isPrime [a..b]

main :: IO ()
main = do
       let lower = 10
           upper = 20
       print (primesInRange lower upper)

Output

[11,13,17,19]

Example 2

In this example, we are going to see that how we can display prime numbers between two interval using list comprehension.

import Data.List (filter)

isPrime :: Integer -> Bool
isPrime n
   | n <= 1 = False
   | n == 2 = True
   | n `mod` 2 == 0 = False
   | otherwise = all (\x -> n `mod` x /= 0) [3,5..(floor (sqrt (fromIntegral n)))]
   
primesInRange :: Integer -> Integer -> [Integer]
primesInRange a b = filter isPrime [a..b]

main :: IO ()
main = do
       let lower = 10
           upper = 20
       print (primesInRange lower upper)

Output

[11,13,17,19]

Conclusion

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In Haskell, to display the prime numbers between two interval we can use user-defined functions and list comprehension.

Updated on: 13-Mar-2023

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements