
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@gmail.com