fork download
  1. {-# OPTIONS_GHC -O2 -v -rtsopts -with-rtsopts="-sstderr" #-}
  2.  
  3. module Main where
  4.  
  5. type Nat = Int -- stackoverflow.com/a/42122559/849891
  6.  
  7. data Heap = Leaf !Nat !Nat -- by stackoverflow.com/users/2144669/david-eisenstat
  8. | Branch !Nat !Heap !Heap
  9. deriving Show
  10.  
  11. top :: Heap -> Nat
  12. top (Leaf n _) = n
  13. top (Branch n _ _) = n
  14.  
  15. leaf :: Nat -> Heap
  16. leaf p = Leaf (3 * p) p
  17.  
  18. branch :: Heap -> Heap -> Heap
  19. branch h1 h2 = Branch (min (top h1) (top h2)) h1 h2
  20.  
  21. pop :: Heap -> Heap -- popAndReinsert, really
  22. pop (Leaf n d) = Leaf (n + 2*d) d
  23. pop (Branch _ h1 h2)
  24. = case compare (top h1) (top h2) of
  25. LT -> branch (pop h1) h2
  26. EQ -> branch (pop h1) (pop h2)
  27. GT -> branch h1 (pop h2)
  28.  
  29. push :: Nat -> Heap -> Heap
  30. push p h@(Leaf _ _) = branch (leaf p) h
  31. push p (Branch _ h1 h2) = branch (push p h2) h1
  32.  
  33. primes0 :: [Nat] -- original definition
  34. primes0
  35. = let helper n h
  36. = case compare n (top h) of
  37. LT -> n : helper (n + 2) (push n h)
  38. EQ -> helper (n + 2) (pop h)
  39. GT -> helper n (pop h)
  40. in 2 : 3 : helper 5 (leaf 3)
  41.  
  42. main = do
  43. print (primes0 !! 800000)
Success #stdin #stdout 12.64s 8388607KB
stdin
Standard input is empty
stdout
12195263