Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active May 28, 2021 19:11
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 ericnormand/2d21bd06c44b37cd7ac34137ef46b249 to your computer and use it in GitHub Desktop.
Save ericnormand/2d21bd06c44b37cd7ac34137ef46b249 to your computer and use it in GitHub Desktop.
428 PurelyFunctional.tv Newsletter

Formatted prime factorization

Prime factorization means representing an integer as a product of primes. A function that factorizes a number will return a vector of primes, like so: [2 2 3 5]. Your job is to take such a vector and create a nice string that shows the mathematical notation of the product.

Examples

(format-product [2 2 3 5]) ;=> "2^2 x 3 x 5"
(format-product [2 3 3 3 11 11]) ;=> "2 x 3^2 x 11^2"
(format-product [7]) ;=> "7"

Use x to indicate multiplication and ^ to indicate exponentiation.

Thanks to this site for the problem idea, where it is rated Hard in Ruby. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://purelyfunctional.tv/newsletter/

@vpetruchok
Copy link

(defn format-product [xs]
  (->> (frequencies xs)
       (sort-by first)
       (reduce (fn [res [n cnt]]
                 (str
                  res
                  (if (empty? res) "" " x ")
                  (if (= cnt 1) n (str n "^" cnt))))
               "")))

@mchampine
Copy link

(defn ffact [[fk fv]] (if (= fv 1) (str fk) (str fk "^" fv)))

(defn format-product [pf]
  (apply str (interpose " x " (map ffact (frequencies pf)))))

@jaihindhreddy
Copy link

(defn format-product [nums]
  (->> (into (sorted-map) (frequencies nums))
       (map (fn [[x n]] (if (= n 1) x (str x \^ n))))
       (clojure.string/join " x ")))

The into call can be skipped if we don't care about order.

@miner
Copy link

miner commented May 28, 2021

(defn string-builder
  ([] (StringBuilder.))
  ([sb] (str sb))
  ([sb x] (.append ^StringBuilder sb (str x))))

(defn format-product [factors]
  (transduce (comp (map (fn [[f cnt]] (if (= cnt 1) f (str f "^" cnt))))
                   (interpose " x "))
             string-builder
             (sort (frequencies factors))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment