The sieve of Sundaram: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Dropped use of Data.Set)
(Undo revision 340192 by Hout (talk))
Line 284: Line 284:
<lang haskell>import Data.List (intercalate, transpose)
<lang haskell>import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.List.Split (chunksOf)
import qualified Data.Set as S
import Text.Printf (printf)
import Text.Printf (printf)


Line 289: Line 290:


sundaram :: Integral a => a -> [a]
sundaram :: Integral a => a -> [a]
sundaram n = succ . (2 *) <$> gaps [1 ..] excluded
sundaram n =
[ succ (2 * x)
| x <- [1 .. m],
x `S.notMember` excluded
]
where
where
m = div (pred n) 2
m = div (pred n) 2
excluded =
excluded =
[ 2 * i * j + i + j
S.fromList
| let fm = fromIntegral m,
[ 2 * i * j + i + j
i <- [1 .. floor (sqrt (fm / 2))],
| let fm = fromIntegral m,
let fi = fromIntegral i,
i <- [1 .. floor (sqrt (fm / 2))],
j <- [i .. floor ((fm - fi) / succ (2 * fi))]
let fi = fromIntegral i,
j <- [i .. floor ((fm - fi) / succ (2 * fi))]
]
]


nSundaramPrimes ::
nSundaramPrimes ::
Line 304: Line 310:
nSundaramPrimes n =
nSundaramPrimes n =
sundaram $ floor $ (2.4 * n * log n) / 2
sundaram $ floor $ (2.4 * n * log n) / 2





Line 312: Line 319:
(putStrLn . table " " . chunksOf 10) $
(putStrLn . table " " . chunksOf 10) $
show <$> nSundaramPrimes 100
show <$> nSundaramPrimes 100


------------------------- GENERIC ------------------------

gaps _ [] = []
gaps (x : xs) yys@(y : ys)
| x >= y = gaps xs ys
| otherwise = x : gaps xs yys


table :: String -> [[String]] -> String
table :: String -> [[String]] -> String