Monday, August 25, 2014

Kata: Prime factors in Clojure

I've just done the Prime factors kata in Clojure.

These are the tests using Midje:

(ns prime-factors.core-test
(:use midje.sweet)
(:use [prime-factors.core]))
(facts
"about prime factors computation"
(fact "1 has no factors"
(factorize 1) => [])
(fact "a prime has only one factor: itself"
(factorize 2) => [2]
(factorize 3) => [3])
(fact "any power of primes has only one factor repeated as many times as the exponent"
(factorize 8) => [2 2 2]
(factorize 81) => [3 3 3 3])
(fact "any other positive integer has more than one factor"
(factorize 10) => [2 5]
(factorize 60) => [2 2 3 5]))

and this is the code:

(ns prime-factors.core)
(def ^:private factor?
(comp zero? rem))
(defn factorize [n]
(loop [n n prime 2 factors []]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))

You can find the commits step by step here.

No comments:

Post a Comment