Loading [MathJax]/jax/output/CommonHTML/jax.js

Problem 020: Factorial digit sum

From Project Euler:

n! means n×(n1)×...×3×2×1

For example, 10!=10×9×...×3×2×1=3628800,
and the sum of the digits in the number 10!is3+6+2+8+8+0+0=27.

Find the sum of the digits in the number 100!

This is pretty straight-forward, since Clojure supports arbitrary precision arithmetic. You just have to be a bit careful when writing factorial to ensure that it actually uses them instead of just overflowing:
(defn factorial [n]
  (reduce * (range 1N n)))
In Problem 008 we had to calculate the product of the digits of a number. Since here we're calculating the sum, I figured I'd create a function that reduces the digits of a number according to some function, and define a few specializations of it:
(defn reduce-digits [f n]
  "Reduce the digits of `n` using some function."
  (loop [current (quot n 10)
         total (mod n 10)]
    (if (== 0 current)
      total
      (recur (quot current 10)
             (f total (mod current 10))))))

(defn prod-digits [n]
  "Multiply the digits of `n` together."
  (reduce-digits * n))

(defn sum-digits [n]
  "Add the digits of `n` together."
  (reduce-digits + n))
After that, our code is pretty straight-forward:
(defn sum-factorial-digits [n]
  (sum-digits (factorial n)))
This runs very fast:
$ lein run
Processing...
648N
"Elapsed time: 5.780961 msecs"

No comments:

Post a Comment