Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created October 19, 2021 14:24
Show Gist options
  • Save ericnormand/642261cb154219ec6c1fb01c6cab33f9 to your computer and use it in GitHub Desktop.
Save ericnormand/642261cb154219ec6c1fb01c6cab33f9 to your computer and use it in GitHub Desktop.
447 PurelyFunctional.tv Newsletter

Product of digits of sum

Write a function that takes one or more numbers as arguments. It should sum them, then multiply the digits. If the answer is one digit long, it's done. If it's more than one digit, repeat and multiply the digits again.

Examples

(sum-prod 4) ;=> 4
(sum-prod 10) ;=> 0 (since the sum is two digits, then 1 * 0)
(sum-prod 11 12) ;=> 6
(sum-prod 12 16 223) ;=> 0 (work it out!)

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

Please submit your solutions as comments on this gist.

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

@stuartstein777
Copy link

@dhoboy

put clojure after your first ` tags

@jumarko
Copy link

jumarko commented Jan 26, 2022

https://github.com/jumarko/clojure-experiments/blob/master/src/clojure_experiments/purely_functional/puzzles/0447_longest_alternating_substring.clj#L1

(defn- multiply-digits [number]
  (apply * (mapv (comp parse-long str) (str number))))

(defn sum-prod
  "Takes one or more numbers as arguments.
  Sum them, then multiply the digits.
  If the answer is one digit long, it’s done.
  If it’s more than one digit, repeat and multiply the digits again."
  [& numbers]
  (let [sum (apply + numbers)]
    (loop [num sum]
      (let [product (multiply-digits num)]
        (if (< 9 product)
          (recur product)
          product)))))

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