Skip to content

Instantly share code, notes, and snippets.

@weaver
Created October 16, 2014 13:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaver/f7321163391f6ae45ce0 to your computer and use it in GitHub Desktop.
Save weaver/f7321163391f6ae45ce0 to your computer and use it in GitHub Desktop.
Naive Primes in Clojure
;;; 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