Skip to content

Instantly share code, notes, and snippets.

@Vinai
Created September 22, 2017 08:58
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 Vinai/a4d6c56e1a92f388edb72ffd30513733 to your computer and use it in GitHub Desktop.
Save Vinai/a4d6c56e1a92f388edb72ffd30513733 to your computer and use it in GitHub Desktop.
Prime factors kata early in me learning Clojure
(ns prime-factors.core)
(defn generate-recursive
"Prime factor kata that does not use tail call optimization"
([n] (generate-recursive n [] 2))
([n primes candidate]
(if (= 1 n)
primes
(if (= 0 (mod n candidate))
(generate-recursive (/ n candidate) (conj primes candidate) candidate)
(generate-recursive n primes (inc candidate))))))
(defn generate
"Tail call form of the prime factors kata"
([n] (generate n [] 2))
([n primes candidate]
(if (= 1 n)
primes
(if (= 0 (mod n candidate))
(recur (/ n candidate) (conj primes candidate) candidate)
(recur n primes (inc candidate))))))
(defn generate-loop
"Tail call optimized version using loop"
[num]
(loop [n num
primes []
candidate 2]
(if (= 1 n)
primes
(if (= 0 (mod n candidate))
(recur (/ n candidate) (conj primes candidate) candidate)
(recur n primes (inc candidate))))))
(ns prime-factors.core-test
(:require [clojure.test :refer :all]
[prime-factors.core :refer :all]))
(deftest prime-factors
(testing "generating the prime factors of 1"
(is (= [] (generate 1))))
(testing "generating the prime factors of 2"
(is (= [2] (generate 2))))
(testing "generating the prime factors of 3"
(is (= [3] (generate 3))))
(testing "generating the prime factors of 4"
(is (= [2 2] (generate 4))))
(testing "generating the prime factors of 6"
(is (= [2 3] (generate 6))))
(testing "generating the prime factors of 8"
(is (= [2 2 2] (generate 8))))
(testing "generating the prime factors of 9"
(is (= [3 3] (generate 9))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment