Download code

Jump to: navigation, search

Back to Sieve_of_Eratosthenes_(Haskell)

Download for Windows: zip

Download for UNIX: zip, tar.gz, tar.bz2

prime_sieve_naive_test.hs

 1 {- The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)?oldid=19210
14 -}
15 
16 module Main
17   where
18 
19 
20 primes :: [Integer]
21 primes = sieve [2..]
22   where
23     sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
24 
25 
26 main :: IO ()
27 main = do
28   print $ show (primes !! 10000)


hijacker
hijacker
hijacker
hijacker

prime_sieve_better_test.hs

 1 {- The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)?oldid=19210
14 -}
15 
16 module Main
17   where
18 
19 
20 merge :: (Ord a) => [a] -> [a] -> [a]
21 merge xs@(x:xt) ys@(y:yt) = 
22   case compare x y of
23     LT -> x : (merge xt ys)
24     EQ -> x : (merge xt yt)
25     GT -> y : (merge xs yt)
26 
27 diff :: (Ord a) => [a] -> [a] -> [a]
28 diff xs@(x:xt) ys@(y:yt) = 
29   case compare x y of
30     LT -> x : (diff xt ys)
31     EQ -> diff xt yt
32     GT -> diff xs yt
33 
34 primes, nonprimes :: [Integer]
35 primes    = [2, 3, 5] ++ (diff [7, 9 ..] nonprimes) 
36 nonprimes = foldr1 f $ map g $ tail primes
37   where 
38     f (x:xt) ys = x : (merge xt ys)
39     g p         = [ n * p | n <- [p, p + 2 ..]]
40 
41 main :: IO ()
42 main = do
43   print $ show (primes !! 10000)


hijacker
hijacker
hijacker
hijacker