ã¨ã©ãã¹ããã¹ã®å°åé«éé å¿åé¢æ©
å ¨å½ã® Haskell使ãã®ã¿ãªãã Golferã®ã¿ãªããï¼ç¸®ã¿ã¾ãã¦ããã§ã¨ããããã¾ãï¼ä»å¹´ããããããããããã¾ãï¼
ä»åã®è©±é¡ã¯2011å¹´ã¨ãããã¨ãããç´ æ°åé¡å¾¡ç¨éã¨ã©ãã¹ããã¹ã®ç¯©ï¼æ£ç´ããããªäººãã¨ãä¸ãã¦ããã¼ãã ããæ¬é¡ã®ãã¿ããã¶ã£ã¦ãªããã¨æ¦ã æã ã ï¼
ããHaskellã®å ¥éè¨äºã«ãåºãã¿ãããªã®ã§ç´ æ°ç¡éãªã¹ãã®åºæ¬åã¯ã¿ããª10ç§ãããã§æ¸ããã¨æããããã©ä¸å¿ç´¹ä»ããã¨ï¼
-- 37æåºæ¬å p=f[2..];f(p:x)=p:f[n|n<-x,mod n p>0]
ãã®åºæ¬åã¯ã¨ã£ã¦ãé ãï¼å°ããç´ æ°ã¾ã§ãã使ããªãåé¡ãªãã¾ã ããï¼å¤§ããªç´ æ°ãå¿ è¦ãªåé¡ã«ãªãã¨è²«ç¦ã®TLEããã£ã¦ï¾ï½°ï¾ï½¯ï¾ï½°FATAL K.O.ãªã®ãã¾ãæåãªè©±ã§ï¼ã¾ãã«youã¯shockï¼anarchy golf ã§ã¯ãããªå¤§ããªç´ æ°ã¯ãã¾ãåºã¦ããªããã©ï¼ä»ã®ã´ã«ãå ´ã¨ãå ã ã´ã«ãæ¨ããããªãã²ã¼ã»ã³ã§ã´ã«ããã¬ã¤ããã¨ï¼æéå¶éã®å£ãéãã®ããããï¼
ã¸ã£ãã¸ã·ã¹ãã ã俺ã¯ãã®ã¾ã¾ã¿ã¤ã ã¢ããã§ããããã ãï¼ã
ã®ã§ï¼ãããã£ãåé¡ãä½ææ°ã§å¦çããããã«ã¯çããªããããããªãã«éã篩ãå¿ è¦ã¨ãªãï¼
åºæ¬åã¯Intä»ãããå¶æ°æããããããã¦ã2åç¨åº¦ã®é«éåãã§ããï¼ãããªãããããå ¨ç¶è¶³ããªãï¼
-- å¶æ°æã p=2:f[3,5..];f(p:x)=p:f[n|n<-x,mod n p>0] -- Intä»ã p=f[2..];f(p:x)=p:f[n::Int|n<-x,mod n p>0]
æå¤§å ¬ç´æ°ã¨å¤åé·æ´æ°ãå ±ã«å®ãè¨èªç¨ã®ããªã¨ã¼ã·ã§ã³ã¨ãã¦ï¼ãããªã®ããã£ãããã
-- 45æå¤åå p=1#2;a#b|gcd a b<2=b:(a*b)#(b+1)|0<1=a#(b+1)
ãï¼ããã«ããã£ã¦æå ã®ç°å¢ã§ã¯3åããããªããããã§ãããªãï¼
ãããªããã§æ¬æ¥ãªã¹ã¹ã¡ããååã¯ã³ãã©ï¼
-- 62æé«éå p=2:3:2#p;m#(a:b:x)=[n|n<-[a^2..b^2-2],gcd m n<2]++(m*b)#(b:x)
ææ©æ¯è¼ããæå³ç¡ãã¬ãã«ã®é度差ãªã®ã§ï¼é«éåã®ã¿1000000çªç®ãåºåããæéã測ãã¨ï¼
$ uname -a Linux scarlet 2.6.26.8-co-0.7.7.1 #1 PREEMPT Fri Jul 2 17:00:57 UTC 2010 i686 Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz GenuineIntel GNU/Linux $ cat prime.hs main=print$p!!999999 p=2:3:2#p;m#(a:b:x)=[n|n<-[a^2..b^2-2],gcd n m<2]++(m*b)#(b:x) $ ghc --version The Glorious Glasgow Haskell Compilation System, version 6.12.3 $ ghc -O --make prime.hs $ time ./prime 15485863 real 0m11.260s user 0m10.410s sys 0m0.840s
ã¨ï¼å¤§ä½11ç§å¼·ã«ãªãï¼
ã¾ãï¼å¶æ°æããå®æ½ãã¦ï¼
-- 76æé«éåwithå¶æ°æã p=2:q;q=3:5:7:3#q;m#(a:b:x)=[n|n<-[a^2,a^2+2..b^2-2],gcd n m<2]++(m*b)#(b:x) -- (追è¨)68æé«éåwithå¶æ°æã(thx koyama41) p=2:3:1#p;m#(a:b:x)=[n|n<-[a^2..b^2-2],odd n,gcd n m<2]++(m*b)#(b:x)
ã¾ã§ããããã°ï¼
$ time ./prime 15485863 real 0m6.230s user 0m5.570s sys 0m0.660s
ã¨ï¼6ç§å¼·ããã(追è¨:68æçã¯76æçããè¥å¹²é ã6.7sç¨åº¦)ã¾ã§ãããã©ï¼14(or 6)æå·®ã¯ã¨ã¦ãæ®å¿µãªå·®ããªï¼
(1/16è¿½è¨ ãããã)
ãããããã£ã¦ããï¼ãããªã®ãã§ããï¼
-- 66æé«éåwithå¶æ°æã p=2:3:5#p;n#x@(m:p:y)=[n|gcd m n<2]++(n+2)#last(x:[m*p:y|p^2-3<n])
koyama41ããæ¡ã®68æç¸å½ã®é度ã§66æã¨ãã£ãããªã¼ãºããã«ã«ï¼
(1/16è¿½è¨ ããã¾ã§)
åé¡ã®è³ªã«ãã£ã¦ï¼ã¾ã«ããä¸ã§æçãé¸ã¶ã£ã¦ãã³ã¯è¨ãã¾ã§ããªããã©ï¼å¤§æµåºæ¬åãä»åã®é«éåã®2æã§ãã¨ãããã¯ãï¼
å ¥éè¨äºã®ä¸ã§gcdã®å®ãã§ç´ æ°ã»æ´æ°ç³»åé¡ã®è§£ãæ¹ãããã¬ãã£ã¦æ¸ãããã¿ã®ã²ã¨ã¤ã¨ãã¦ãããªä½¿ãæ¹ã¢ã«ã¨ã£ã¦ãã¨ã§ä»åã¯ããã¾ã§ï¼