fork download
  1. {-# OPTIONS_GHC -O2 -fno-cse #-}
  2. main = do
  3. let m = 1000000
  4. putStr $ show m ++ "-th prime: "
  5. print $ tmawprimes !! (m - 1)
  6.  
  7. data A a = A a (A a) | B [a] -- direct encoding for Split List
  8.  
  9. tmawprimes :: [Int]
  10. tmawprimes = 2:3:5:7:primes' -- tree-merged | primes-multiples removal
  11. where -- | with 2-3-5-7 WHEEL
  12. primes' = roll 11 wheel `minus` tjoin
  13. [A (p*p) (B [p*q|q<-rollFrom p]) | p <- primes_]
  14.  
  15. primes_ = h ++ t `minus` tjoin
  16. [A (p*p) (B [p*q|q<-rollFrom p]) | p <- primes_]
  17. where (h,t) = splitAt 6 (roll 11 wheel)
  18.  
  19. rollFrom n = go wheelNums wheel
  20. where m = (n-11) `mod` 210
  21. go (x:xs) (w:ws) | x==m = roll (n+w) ws
  22. | True = go xs ws
  23. wheelNums = roll 0 wheel -- [0,2,6,8,12,18, ...]
  24. roll = scanl (+)
  25. wheel = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:
  26. 4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel
  27.  
  28. tjoin (a:b:c:ys) = add a (add b c) `add` tjoin (pairs ys)
  29. where pairs (a:b:ys) = add a b : pairs ys
  30. add u@(B(x:xs)) v@(A y ys) = case compare x y of
  31. LT -> A x (add (B xs) v)
  32. EQ -> A x (add (B xs) ys)
  33. GT -> A y (add u ys)
  34. add (A x xs) v = A x (add xs v)
  35. add (B xs) (B ys) = B (union xs ys)
  36.  
  37. union a@(x:xs) b@(y:ys) = case compare x y of
  38. LT -> x : union xs b
  39. EQ -> x : union xs ys
  40. GT -> y : union a ys
  41.  
  42. minus a@(x:xs) b@(A y ys) = case compare x y of
  43. LT -> x : minus xs b
  44. EQ -> minus xs ys
  45. GT -> minus a ys
stdin
Standard input is empty
compilation info
[1 of 1] Compiling Main             ( prog.hs, prog.o )
Linking prog ...
stdout
1000000-th prime: 15485863