- Open src/Main.hs; we will add our prime number generator here.
- We will start with 2 as the initial prime number and continue with only odd numbers; this will remove all the factors of 2.
- We will assume that there are infinite prime numbers. We can write a list of primes as follows:
primes :: [Integer]
primes= 2 : filterMultiples allMultiples [3,5..]
where
allMultiples = mergeMultiples $ map multiples primes
multiples i = map (i*) [i..]
Here, allMultiples are all multiples of all the primes; filterMultiples will weed out all those multiples from the list of odd numbers [3,5..]. All multiples are found out by lazily going over the primes that we are calculating and finding multiples of each.
- We need to implement filterMultiples to weed out composites, merge to merge two list of multiples, and mergeMultiples to recursively merge all multiples of primes:
filterMultiples :: Ord a => [a] -> [a] -> [a]
filterMultiples (f:fs) (x:xs) | f < x = filterMultiples fs
(x:xs)
| f > x = x : filterMultiples (f:fs) xs
| otherwise = filterMultiples fs xs
merge :: Ord a => [a] -> [a] -> [a]
merge (x:xs) (y:ys) | x < y = x : merge xs (y:ys)
| x > y = y : merge (x:xs) ys
| otherwise = x : merge xs ys
mergeMultiples :: Ord a => [[a]] -> [a]
mergeMultiples ((x:xs):xss) = x : merge xs (mergeMultiples xss)
- Finally, we can test our prime numbers by checking the 1000th prime number (https://en.wikipedia.org/wiki/List_of_prime_numbers#The_first_1000_prime_numbers):
main :: IO ()
main = do
let prime1k = take 1000 primes
prime1kth = prime1k !! 999
putStrLn $ "1000th prime number is " ++ (show prime1kth)
- If you build the project and run it, then you should see the 1000th prime number: