I am currently working on trying to find the number of primes between a range in haskell. The program prints out the range of primes correctly. E.g countPrimesUntil 2 10 will print out [2, 3, 5, 7]. I am looking for the number 4 because that's how many primes is between 2 and 10. How do I incorporate countPrimes correctly?
import Data.List
countPrimesUntil :: Integral a=> a -> a -> [a]
countPrimesUntil a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..]
while sieve (n:ns) = n:sieve [m | m <- ns, m `mod` n /= 0]
countPrimes n = length([x | x <- [2..n], countPrimesUntil x])
CodePudding user response:
countPrimesUntil
is misnamed; it doesn't count anything. Rather, it produces a list of primes between a
and b
, inclusive.
All you need to do is apply length
to the result of countPrimesUntil
, when given arguments 2
and n
.
countPrimes n = length (countPrimesUntil 2 n)
-- countPrimes = length . countPrimesUntil 2
CodePudding user response:
In that case the countPrimes
calls countPrimesUntil 2 n
, and determines it length, so:
countPrimes n = length (countPrimesUntil 2 n)