[Haskell-beginners] Performance of Prime Generator
Zhi-Qiang Lei
zhiqiang.lei at gmail.com
Sat Jan 21 09:27:38 CET 2012
Hi,
I have bungled the Prime Generator on SPOJ for many times. Although the program is faster and faster on my machine, but it keeps "time limited exceeded" on SPOJ (6 seconds limit). Now my approach is for every number in the range, check if it is prime by checking if can be divided by all the primes smaller than or equal its square root. For the numbers between 999900000 and 1000000000, it take 0.64 seconds on my laptop. Could anyone give me some hints to enhance it? Thanks.
=== Test Data ===
1
999900000 1000000000
=== Test Data ===
=== Code ===
{-# OPTIONS_GHC -O2 -fno-cse #-}
import System.IO
data Wheel a = Wheel a [a]
roll :: Integral a => Wheel a -> [a]
roll (Wheel n rs) = [n*k+r | k <- [0..], r <- rs]
nextSize :: Integral a => Wheel a -> a -> Wheel a
nextSize (Wheel n rs) p =
Wheel (p*n) [r' | k <- [0..(p-1)], r <- rs,
let r' = n*k+r, r' `mod` p /= 0]
mkWheel :: Integral a => [a] -> Wheel a
mkWheel ds = foldl nextSize (Wheel 1 [1]) ds
primes :: Integral a => [a]
primes = small ++ large where
1:p:candidates = roll $ mkWheel small
small = [2,3,5,7]
large = p : filter isPrime candidates
isPrime n = all (not . divides n)
$ takeWhile (\p -> p*p <= n) large
divides :: Integral a => a -> a -> Bool
divides n p = n `mod` p == 0
sqrt' :: Integral a => a -> a
sqrt' = floor . sqrt . fromIntegral
primesFromTo :: [Int] -> [Int]
primesFromTo [x, y] = filter isPrime [x..y]
isPrime :: Integral a => a -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n = all (not . divides n) $ takeWhile (<= sqrt' n) primes
main :: IO ()
main = do
count <- fmap read getLine
inputLines <- fmap (take count . lines) getContents
let answers = map (primesFromTo . map read . words) inputLines
putStr . unlines . map (unlines . map show) $ answers
=== Code ===
Best regards,
Zhi-Qiang Lei
zhiqiang.lei at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120121/110e71ec/attachment.htm>
More information about the Beginners
mailing list