{-# OPTIONS_GHC -O2 #-}
module Main where
import Data. List ( tails)
main
= print $ primes
!! 1000000 -- -fno-cse -fno-full-laziness
primes0 = _ Y $ ( 2 :) . minus [ 3 .. ] .
foldr ( \p
-> ( p
* p :
) . union
[ p
* p
+ p
, p
* p
+ 2 * p
.. ] ) [ ]
primes
= [ 2 , 3 , 5 , 7 ] ++ _ Y
( ( 11 :
) . tail . minus
( scanl ( + ) 11 wh11
) . foldi ( \( x:xs) -> ( x:) . union xs)
. map ( \
( w
, p
) -> scanl ( \c d
-> c
+ p
* d
) ( p
* p
) w
)
wh3 = 2 :wh3 -- ([3],2) {1*2,2*3}
wh5 = 2 :4 :wh5 -- ([5,7],6) {2*4,6*5}
wh7 = 4 :2 :4 :2 :4 :6 :2 :6 :wh7 -- ([7,11,13,17,19,23,29,31],30) {8*6,30*7}
wh11 = 2 :4 :2 :4 :6 :2 :6 :4 :2 :4 :6 :6 :2 :6 :4 :2 :6 :4 :6 :8 :4 :2 :4 :2 :
4 :8 :6 :4 :6 :2 :4 :6 :2 :6 :6 :4 :2 :4 :6 :2 :6 :4 :2 :4 :2 :10 :2 :10 :wh11
_ Y g = g ( _ Y g) -- multistage with non-sharing fixpoint combinator
-- = g (fix g) -- two stages with sharing fixpoint combinator
foldi f ( xs:t) = f xs . foldi f . pairs f $ t
pairs f ( x:y:t) = f x y : pairs f t
union a
@ ( x:xs
) b
@ ( y:ys
) = case compare x y
of LT -> x : union xs b
EQ -> x : union xs ys
GT -> y : union a ys
minus a
@ ( x:xs
) b
@ ( y:ys
) = case compare x y
of LT -> x : minus xs b
EQ -> minus xs ys
GT -> minus a ys
equalsBy f a
@ ( x:xs
) b
@ ( y:ys
) = case compare ( f x
) y
of LT -> equalsBy f xs b
EQ -> x : equalsBy f xs ys
GT -> equalsBy f a ys
ey0jIE9QVElPTlNfR0hDIC1PMiAjLX0KbW9kdWxlIE1haW4gd2hlcmUKaW1wb3J0IERhdGEuTGlzdCAodGFpbHMpICAKbWFpbiA9IHBy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mcgY2hhbmdlZCBvbiAyMDEzLTA3LTMxOgotLSBzdWRkZW5seSBgbWludXMgKHNjYW5sICgrKSAxMSB3aDExKWAgZG9lc24ndCBjYXVzZSBIVUdFIHNwYWNlIGxlYWsgYW55bW9yZSAhPz8hIQotLSAgYW5kIHJ1bnMgc2xvd2VyIHRoYXQgZ2Fwcy9oaXRzIChzZWUgdmtYQ1h0KS4gLS0gSURFT05FIFNXSVRDSEVEIGZyb20gNy40LjEgdG8gNy42LjMgIS4uLi4KLS0gKG1hcCAocCopICQgc2NhbmwgKCspIHAgdyk6IDMuMTVzIC4uLiA2LjkxcyAsIDkuMyBNQiAgIG5eMS4xMwoKLS0gLi4uLi4uIGFuZCBpbiA3LjguMyBpdCBMRUFLUyBBR0FJTiBsaWtlIGNyYXp5ISEgICBvbmx5IGdhcHMvaGl0cyBkb2Vzbid0IGxlYWs=
1mln: 2.50s - 9.4 M ordmergeBy : 4.44s - 9.4 M
2mln: 5.90s - 9.3 M n^1.24 9.91s - 9.4 M n^1.16
3mln: 9.29s - 9.4 M n^1.12
-- something changed on 2013-07-31:
-- suddenly `minus (scanl (+) 11 wh11)` doesn't cause HUGE space leak anymore !??!!
-- and runs slower that gaps/hits (see vkXCXt). -- IDEONE SWITCHED from 7.4.1 to 7.6.3 !....
-- (map (p*) $ scanl (+) p w): 3.15s ... 6.91s , 9.3 MB n^1.13
-- ...... and in 7.8.3 it LEAKS AGAIN like crazy!! only gaps/hits doesn't leak