Advertisement
clairec

prime sieve

Sep 13th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Here is an inefficient (but easier to understand) definition of the
  2. -- infinite list of all prime numbers
  3. primes_slow = sieve [2..] where
  4.   sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
  5.  
  6. -- Here is a much more efficient (but harder to understand) version of primes.
  7. -- Try "take 100 primes" as an example (or even more if you like)
  8. primes = 2 : primesFrom3 where
  9.     primesFrom3 = sieve [3,5..] 9 primesFrom3
  10.     sieve (x:xs) b ~ps@(p:q:_)
  11.       | x < b     = x : sieve xs b ps
  12.       | otherwise =     sieve [x | x <- xs, rem x p /= 0] (q^2) (tail ps)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement