Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell, counting how many prime numbers are there in a list

i m a newbie to haskell, currently i need a function 'f' which, given two integers, returns the number of prime numbers in between them (i.e., greater than the first integer but smaller than the second).

Main>  f 2 4
1
Main> f 2 10
3

here is my code so far, but it dosent work. any suggestions? thanks..

f :: Int -> Int -> Int
f x y 
  | x < y = length [ n | n <- [x..y], y 'mod' n == 0] 
  | otherwise = 0
like image 229
sefirosu Avatar asked Nov 30 '25 14:11

sefirosu


1 Answers

  • Judging from your example, you want the number of primes in the open interval (x,y), which in Haskell is denoted [x+1 .. y-1].
  • Your primality testing is flawed; you're testing for factors of y.
  • To use a function name as an infix operator, use backticks (`), not single quotes (').

Try this instead:

-- note: no need for the otherwise, since [x..y] == [] if x>y
nPrimes a b  =  length $ filter isPrime [a+1 .. b-1]

Exercise for the reader: implement isPrime. Note that it only takes one argument.

like image 192
Fred Foo Avatar answered Dec 03 '25 15:12

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!