clairec icon

prime sieve

clairec | PRO | 09/14/16 02:42:49 AM UTC | 0 ⭐ | 465 👁️ | Never ⏰ | []
Haskell |

560 B

|

None

|

0 👍

/

0 👎

-- Here is an inefficient (but easier to understand) definition of the
-- infinite list of all prime numbers
primes_slow = sieve [2..] where
  sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0]
 
-- Here is a much more efficient (but harder to understand) version of primes.
-- Try "take 100 primes" as an example (or even more if you like)
primes = 2 : primesFrom3 where 
    primesFrom3 = sieve [3,5..] 9 primesFrom3
    sieve (x:xs) b ~ps@(p:q:_)
      | x < b     = x : sieve xs b ps
      | otherwise =     sieve [x | x <- xs, rem x p /= 0] (q^2) (tail ps)

Comments