Search code examples
haskellprimes

How to provide a specific range of inputs to a function in Haskell


I'm new to Haskell and I'm wondering if it's possible to provide a range of the first 51 prime numbers as input rather than typing the prime numbers, see line 2 ?

If so, please modify the code and post the solution.

  1 perfect_nums n = (2^(n-1)) * ((2^n)-1)
  2 fperfect_nums = [perfect_nums x | x <- [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233]]
  3 main = print $ fperfect_nums


Solution

  • You can write a function to generate primes or use a library. I like to use arithmoi for this purpose:

    import Math.NumberTheory.Primes (nextPrime, unPrime)
    
    perfectNums :: Integer -> Integer
    perfectNums n = (2^(n-1)) * ((2^n)-1)
    
    fperfectNums :: [Integer]
    fperfectNums = [perfectNums (unPrime x) | x <- take 51 [nextPrime 0 ..]]
    
    main :: IO ()
    main = print fperfectNums