Loopy

This post was originally published on this site

Clean Coder

The following is a segment of a journey. It has no obvious beginning point, nor does it actually end up anywhere. The value, if any, is in the journey itself.

The code below is the standard solution to the Prime Factors Kata.

public List<Integer> factorsOf(int n) { ArrayList<Integer> factors = new ArrayList<>(); for (int d = 2; n > 1; d++) for (; n % d == 0; n /= d) factors.add(d); return factors; }

However, I was doing this kata in Clojure the other day and I wound up with a different solution. It looked like this:

(defn prime-factors [n] (loop [n n d 2 factors []] (if (> n 1) (if (zero? (mod n d)) (recur (/ n d) d (conj factors d)) (recur n (inc d) factors)) factors)))

The algorithm is pretty

To read the full article click on the 'post' link at the top.