Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created September 29, 2010 08:21
Show Gist options
  • Select an option

  • Save abhin4v/602453 to your computer and use it in GitHub Desktop.

Select an option

Save abhin4v/602453 to your computer and use it in GitHub Desktop.
Solution to SPOJ PRIME1 problem
module Main where
import List
main :: IO ()
main = do
noOfTestCases <- readLn
readTestCases noOfTestCases
readTestCases :: Integer -> IO ()
readTestCases noOfTestCases = do
if noOfTestCases > 0
then do
input <- getLine
let rawLimits = map readInt $ words input
let limits = (rawLimits !! 0, rawLimits !! 1)
putStrLn $ concat . List.intersperse "\n" $ map show $ primesBetween limits
putStrLn ""
readTestCases $ noOfTestCases-1
else
return ()
readInt :: String -> Integer
readInt i = read i :: Integer
primes = 2:3:5:7: filter isPrime [11,13..]
isPrime :: Integer -> Bool
isPrime x
| x == 1 = False
| x == 2 = True
| x == 3 = True
| not $ or [(x + 1) `mod` 6 == 0, (x - 1) `mod` 6 == 0] = False
| otherwise = null . primeDivisors $ x
primeDivisors x = filter (\y -> x `mod` y == 0)
$ takeWhile (<= (ceiling . sqrt . fromInteger $ x)) primes
primesBetween :: (Integer, Integer) -> [Integer]
primesBetween (n1, n2) = takeWhile (<= n2) $ dropWhile (< n1) primes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment