Task: Using your language of choice, implement a program that will a) Prompt the user for 2 numbers, and b) output the number of prime numbers between the two numbers (inclusive.)
Output: A B N
Name:
Anonymous2008-05-09 23:05
>>30
That may be beautiful and short, but it's dog slow. Here's one with a decent performance:
import System
import Data.Array.Unboxed
listUArray :: (IArray UArray e, Ix i) => (i, i) -> [e] -> UArray i e
listUArray = listArray
sieve limit = sieveLoop 1 $ listUArray (1, limit) $ False: repeat True
where
sqrtLimit = floor (sqrt $ fromIntegral limit)
sieveLoop last numbers | prime <= sqrtLimit = prime: sieveLoop prime nextNums
| otherwise = map fst $ filter snd $ assocs numbers
where
prime = fst $ head $ filter snd $ drop last $ assocs numbers
nextNums = numbers // zip (tail [0, prime..limit]) (repeat False)
main = do [lo, hi] <- mapM readIO . words =<< getLine
print $ length $ dropWhile (<lo) $ sieve hi