Created
October 16, 2014 13:42
-
-
Save weaver/f7321163391f6ae45ce0 to your computer and use it in GitHub Desktop.
Naive Primes in Clojure
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
;;; Naive Primes | |
;;; | |
;;; Produce a sequence of primes using a naive trial-division | |
;;; algorithm. This is very slow, but easy to understand at a | |
;;; glance. It's useful for unit testing. | |
;;; | |
;;; Optimizations: | |
;;; | |
;;; + Only test odd numbers for primality | |
;;; + Only do trial division up to the square root | |
(defn sqrt | |
"Return the truncated square root of NUMBER." | |
[number] | |
(long (Math/sqrt (double number)))) | |
(defn factor? | |
"Return true when DIVISOR is a factor of NUMBER." | |
[^long number ^long divisor] | |
(= 0 (rem number divisor))) | |
(defn prime? | |
"Determine if a number is prime by searching for factors." | |
[number] | |
(and (> number 1) | |
(not-any? #(factor? number %) | |
(range 2 (inc (sqrt number)))))) | |
(defn primes | |
"Produce a sequence of prime numbers up to LIMIT, generating them | |
using trial division." | |
[limit] | |
(when (> limit 2) | |
(cons 2 (filter prime? (range 3 limit 2))))) | |
;; Let's try it out! | |
(print (primes 20)) ; ==> (2 3 5 7 11 13 17 19) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment