令 Pi 表示第 i 个素数。现任给两个正整数 M≤N≤104,请输出 PM 到 PN 的所有素数。
输入格式:
输入在一行中给出 M 和 N,其间以空格分隔。
输出格式:
输出从 PM 到 PN 的所有素数,每 10 个数字占 1 行,其间以空格分隔,但行末不得有多余空格。
输入样例:
5 27
输出样例:
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103
解题思路:
haskell 生成无穷序列素数算是经典了,随后每10个打印一行
isPrime :: Int -> Bool
isPrime n = and [n `mod` i /= 0 | i <- [2.. floor (sqrt (fromIntegral n))]]
primes :: [Int]
primes = filter isPrime [2..]
groupByN :: Int -> [a] -> [[a]]
groupByN n xs = if length xs <= n then [xs] else take n xs : groupByN n (drop n xs)
main ::IO ()
main = do
lines <- getLine
let xs = (map read $ words lines) :: [Int]
m = head xs
n = last xs
ps = take n primes
rs = groupByN 10 $ drop (m - 1) ps
mapM_ (putStrLn . unwords . map show) rs