Created
November 9, 2017 18:21
-
-
Save kolja/b125eba00b58d000adb277aa6760f9a2 to your computer and use it in GitHub Desktop.
calculate prime numbers and prime factors with clojure
This file contains 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
(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