Created
September 29, 2010 08:21
-
-
Save abhin4v/602453 to your computer and use it in GitHub Desktop.
Solution to SPOJ PRIME1 problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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