These are the tests using Midje:
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 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:
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 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