2
$\begingroup$

I want to calculate the sum of the product of factorials of the digits of numbers. So for example, when $n=467$ I get:

$$n=467\space\to\space\left(4!\right)\cdot\left(6!\right)\cdot\left(7!\right)=87091200\space\to\space8+7+0+9+1+2+0+0=27\tag1$$

So, when $n=467$ I must get $27$.

How can I write fast code to do that? Thanks in advance and Merry Christmas to everybody.

I wrote the following code:

Total@
  IntegerDigits[
    Product[
      Factorial[Part[IntegerDigits[n], k]],
      {k, 1, Length[IntegerDigits[n]]}
    ]
  ]

Which does the job but is really slow.

$\endgroup$
9
  • 1
    $\begingroup$ I don't think there's a point to parallelization here. There are only ten possible factorials (digits 0 through 9), and you can just memoize those and look them up. $\endgroup$
    – Carl Lange
    Dec 25 '21 at 22:40
  • 4
    $\begingroup$ A little more compact is f[n_] := Total@IntegerDigits[Times @@ Factorial[IntegerDigits[n]]]. $\endgroup$
    – bbgodfrey
    Dec 26 '21 at 0:40
  • 1
    $\begingroup$ Carl's suggestion to memoize the factorials for the digits seems to give a small speedup (~10%) over bbgodfrey's formula directly. Fairly small improvement, might vary between machines. facts = Factorial[Range[10] - 1]; f[n_] := Total@IntegerDigits[Times @@ facts[[IntegerDigits[n] + 1]]] $\endgroup$
    – eyorble
    Dec 26 '21 at 6:33
  • 1
    $\begingroup$ Try this one liner: Composition[Total, IntegerDigits, Times @@ # &, Factorial, IntegerDigits][n] $\endgroup$ Dec 26 '21 at 13:55
  • 1
    $\begingroup$ All solutions given in the comments require about ten seconds on my computer to process a ten-million-digit number. The solution in the question is much slower. $\endgroup$
    – bbgodfrey
    Dec 26 '21 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.