aspirinus

Primes

Jun 4th, 2012
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.Map as Map
  2.  
  3. primes1 = 2 : Prelude.filter isPrime [3..]
  4.  
  5. isPrime x = check primes1 where
  6.     check (p:ps) | p*p > x        = True
  7.                  | x `mod` p == 0 = False
  8.                  | otherwise      = check ps
  9.  
  10.  
  11. primes2 = primes' [2..] Map.empty
  12.    where
  13.      primes' [] table = []
  14.       primes' (x:xs) table =
  15.          case Map.lookup x table of
  16.            Nothing -> x: primes' xs (Map.insert (x*x) [x] table)
  17.             Just facts -> primes' xs (Prelude.foldl reinsert (Map.delete x table) facts)
  18.                where
  19.                  reinsert table prime = Map.insertWith (++) (x+prime) [prime] table
Advertisement
Add Comment
Please, Sign In to add comment