sef*_*osu 3 primes haskell function list
ima新手到haskell,目前我需要一个函数'f',给定两个整数,返回它们之间的素数的数量(即,大于第一个整数但小于第二个整数).
Main> f 2 4
1
Main> f 2 10
3
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的代码,但它起作用了.有什么建议?谢谢..
f :: Int -> Int -> Int
f x y
| x < y = length [ n | n <- [x..y], y 'mod' n == 0]
| otherwise = 0
Run Code Online (Sandbox Code Playgroud)
x,y)中的素数数量,在Haskell中表示[x+1 .. y-1].y.试试这个:
-- note: no need for the otherwise, since [x..y] == [] if x>y
nPrimes a b = length $ filter isPrime [a+1 .. b-1]
Run Code Online (Sandbox Code Playgroud)
为读者练习:实施isPrime.请注意,它只需要一个参数.