Created
May 9, 2011 16:58
-
-
Save swannodette/962877 to your computer and use it in GitHub Desktop.
sieve.clj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(set! *unchecked-math* true) | |
(defmacro iloop [[b t n] & body] | |
`(loop [~@b] | |
(when ~t | |
~@body | |
(recur ~n)))) | |
(defn count-primes [^long n] | |
(let [c (inc n) | |
^booleans prime? (make-array Boolean/TYPE c)] | |
(iloop [(i 2) (<= i n) (inc i)] | |
(aset prime? i true)) | |
(iloop [(i 2) (<= (* i i) n) (inc i)] | |
(if (aget prime? i) | |
(iloop [(j i) (<= (* i j) n) (inc j)] | |
(aset prime? (* i j) false)))) | |
(areduce prime? i r 0 | |
(if (aget prime? i) | |
(inc r) | |
r)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice post!
The use of Java BitSets can further improve performance (30 % on my system):
https://gist.github.com/964676/b26344d3d09dcf66ea66000ec207751aa61bd9e3