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
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
)