Fast Prime Number Generation in Clojure

后端 未结 16 1791
萌比男神i
萌比男神i 2020-12-02 12:30

I\'ve been working on solving Project Euler problems in Clojure to get better, and I\'ve already run into prime number generation a couple of times. My problem is that it is

16条回答
  •  有刺的猬
    2020-12-02 13:01

    Here's another approach that celebrates Clojure's Java interop. This takes 374ms on a 2.4 Ghz Core 2 Duo (running single-threaded). I let the efficient Miller-Rabin implementation in Java's BigInteger#isProbablePrime deal with the primality check.

    (def certainty 5)
    
    (defn prime? [n]
          (.isProbablePrime (BigInteger/valueOf n) certainty))
    
    (concat [2] (take 10001 
       (filter prime? 
          (take-nth 2 
             (range 1 Integer/MAX_VALUE)))))
    

    The Miller-Rabin certainty of 5 is probably not very good for numbers much larger than this. That certainty is equal to 96.875% certain it's prime (1 - .5^certainty)

提交回复
热议问题