Skip to content

Instantly share code, notes, and snippets.

@kolja
Created November 9, 2017 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolja/b125eba00b58d000adb277aa6760f9a2 to your computer and use it in GitHub Desktop.
Save kolja/b125eba00b58d000adb277aa6760f9a2 to your computer and use it in GitHub Desktop.
calculate prime numbers and prime factors with clojure
(ns primes.core)
(defn- primes
"returns a lazy list of prime numbers via the sieve of eratosthenes"
([]
(primes (iterate inc 2)))
([[head & tail]]
(cons head
(lazy-seq (primes (remove #(and (not= % head)
(zero? (mod % head))) tail))))))
(defn factors
"return all prime-factors of a number"
([n]
(factors n [] (primes)))
([n acc prim]
(let [p (first prim)]
(cond
(= n p) (conj acc p)
(zero? (mod n p)) (factors (quot n p) (conj acc p) prim)
:else (factors n acc (rest prim))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment