3 ms·
I commented with a much better version of your clojure code. I'm still not convinced that this is the best way to calculate primes though. Moreover, I could ima
by ibdknox 16y ago
I commented with a much better version of your clojure code. I'm still not convinced that this is the best way to calculate primes though. Moreover, I could imagine coming up with a better implementation that uses a lazy seq to just calculate the next prime when it is needed. Here's the code again:
(defn prime? [n]
(if (even? n)
false
(let [root-plus-one (inc (int (Math/sqrt n)))]
(every? #(> (mod n %) 0) (range 3 root-plus-one 2)))))
(defn primes [n]
(conj (filter prime? (range 3 n)) 2))
As far as I can tell this is also faster on my machine, but as others suggest, I don't know that this is a particularly valuable benchmark.