[Question]
  [
## The challenge is to calculate the digit sum of the factorial of a number.
---
Example
```
Input: 10
Output: 27
```
10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
You can expect the input to be an integer above 0.
Output can be of any type, but the answer should be in the standard base of the coding language.
---
Test cases:
```
10    27
19    45
469   4140
985   10053
```
N.B. Some languages can not support large numbers above 32-bit integers; for those languages you will not be expected to calculate large factorials.
[OEIS link here](https://oeis.org/A004152) thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in characters wins!
  
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
!SO
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IVNP&input=MTA)
```
!   Factorial.
 S  Push characters separately.
  O Sum.
```
[Answer]
## [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes
```
!DS
```
[Try it online!](http://jelly.tryitonline.net/#code=IURT&input=&args=MTA)
Does what you expect:
```
!    Factorial.
 D   Decimal digits.
  S  Sum.
```
[Answer]
## Mathematica, 21 bytes
```
Tr@IntegerDigits[#!]&
```
[Answer]
# C++11, 58 bytes
As unnamed lambda modifying its input:
```
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
One of the rare cases when my C++ code is shorter than the [C code](https://codegolf.stackexchange.com/a/100844/53667).
If you want to suppport larger cases, switch to **C++14** and use:
```
[](auto&n){auto i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
and supply the calling argument with `ull` suffix.
Usage:
```
auto f=
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
;
main() {
  int n=10;
  f(n);
  printf("%d\n",n);
}
```
[Answer]
## Ruby, ~~63~~ ~~61~~ ~~53~~ 38 bytes
New approach thanks to manatwork:
```
->n{eval"#{(1..n).reduce:*}".chars*?+}
```
Old:
```
->n{(1..n).reduce(:*).to_s.chars.map(&:hex).reduce:+}
```
* -3 bytes thanks to Martin Ender
* -5 bytes thanks to G B
[Answer]
# Pyth, ~~7~~ 6 bytes
*Thanks to @Kade for saving me a byte*
`sj.!QT`
[Try it online!](https://pyth.herokuapp.com/?code=sj.%21Q10&input=10&debug=0)
This is my first time using Pyth, so I'm sure that my answer could be golfed quite a bit.
Explanation:
```
s Sum
  j the digits of
    .! the factorial of
      Q the input
    T in base 10
```
[Answer]
## Haskell, ~~41~~ 40 bytes
```
f x=sum$read.pure<$>(show$product[1..x])
```
Usage example: `f 985` -> `10053`.
Make a list from `1`to `x`, calculate the product of the list elements, turn it into its string representation, turn each character into a number and sum them.
Edit: @Angs saved a byte. Thanks!
[Answer]
# Python, 54 bytes
```
f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))
```
**[repl.it](https://repl.it/E6Vu)**
[Answer]
## R, 58 53 bytes
Edit: Saved one byte thanks to @Jonathan Carroll and a couple thanks to @Micky T
```
sum(as.double(el(strsplit(c(prod(1:scan()),""),""))))
```
Unfortunately, with 32-bit integers, this only works for `n < 22`. Takes input from stdin and outputs to stdout.
If one would like higher level precision, one would have to use some external library such as `Rmpfr`:
```
sum(as.numeric(el(strsplit(paste(factorial(Rmpfr::mpfr(scan()))),""))))
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 8 bytes
```
$+$*++,a
```
[Try it online!](http://pip.tryitonline.net/#code=JCskKisrLGE&input=&args=MTA)
**Explanation**
```
      ,a    # range
    ++      # increment
  $*        # fold multiplication
$+          # fold sum
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 8 bytes
```
rim!Ab:+
```
[Try it online!](http://cjam.tryitonline.net/#code=cmltIUFiOis&input=MTA)
### Explanation
```
r   e# Read input.
i   e# Convert to integer.
m!  e# Take factorial.
Ab  e# Get decimal digits.
:+  e# Sum.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes
-3 thanks to @Razetime - i forgot to drop a paren lol
```
+/⍎¨∘⍕∘!
```
Explanation:
```
+/⍎¨∘⍕∘!
       !  ⍝ factorial of ⍵
     ⍕    ⍝ convert to string
  ⍎¨      ⍝ produce digit vector
+/        ⍝ sum all digits
```
Has some problems with factorial of 900, this code will work fine for `⍵>40`:
```
b←({⍵⊣⍵.⎕CY'dfns'}⎕NS⍬).big
↑(+b/(⍎¨∘⍕∘(↑(×b/⍳))))
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmv8ahvqlsQkAgI0HzUNsHQyMJcwdjkfxqQra2v8ai379CKRx0zHvVOBZKKj7oWaf4HqgVKpikYGnDBmZZwprHBfwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes
```
$!@e+
```
[Try it online!](http://brachylog.tryitonline.net/#code=JCFAZSs&input=OTg1&args=Wg)
### Explanation
Basically the described algorithm:
```
$!       Take the factorial of the Input
  @e     Take the elements of this factorial (i.e. its digits)
    +    Output is the sum of those elements
```
[Answer]
# Java 7, 148 bytes
```
int s=1,ret=0;while(i>1){s=s*i; i--;}String y=String.valueOf(s);for(int j=0;j<y.length();j++){ret+=Integer.parseInt(y.substring(j,j+1));}return ret;
```
[Answer]
# Ruby, ~~63 60 53~~ 51 bytes
```
->n{a=0;f=(1..n).reduce:*;f.times{a+=f%10;f/=10};a}
```
Thanks to Martin for golfing help.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 4 bytes
```
fsS#
```
Give input on the command line: `$ pushy facsum.pshy 5`. Here's the breakdown:
```
f      % Factorial of input
 s     % Split into digits
  S    % Push sum of stack
   #   % Output
```
[Answer]
# Octave, 30 bytes
```
@(n)sum(num2str(prod(1:n))-48)
```
Calculates the factorial by taking the product of the list `[1 2 ... n]`. Converts it to a string and subtracts `48` from all elements (ASCII code for `0`). Finally it sums it up :)
[Answer]
## bash (seq,bc,fold,jq), ~~34~~ 33 bytes
Surely not the most elegant but for the challenge
```
seq -s\* $1|bc|fold -1|jq -s add
```
[Answer]
## C, 58 bytes
This is not perfect. Only works ones because a have to be -1 in start. The idea is to use two recursive function in one function. It was not as easy as I first thought.
```
a=-1;k(i){a=a<0?i-1:a;return a?k(i*a--):i?i%10+k(i/10):0;}
```
Usage and understandable format:
```
a = -1;
k(i){
   a = a<0 ? i-1 : a;
   return a ? k(i*a--) : i? i%10+k(i/10) :0;
}
main() {
   printf("%d\n",k(10));
}
```
Edit:
I found metode that let use this function multiple time but then length is 62 bytes. 
```
a,b;k(i){a=b?a:i+(--b);return a?k(i*a--):i?i%10+k(i/10):++b;}
```
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
{[+] [*](2..$_).comb}
```
## Expanded:
```
{  # bare block lambda with implicit parameter ｢$_｣
  [+]           # reduce the following with ｢&infix:<+>｣
    [*](        # reduce with ｢&infix:<*>｣
      2 .. $_   # a Range that include the numbers from 2 to the input (inclusive)
    ).comb      # split the product into digits
}
```
[Answer]
# Cubix, ~~33~~ 32 bytes
```
u*.$s.!(.01I^<W%NW!;<,;;q+p@Opus
```
Net form:
```
      u * .
      $ s .
      ! ( .
0 1 I ^ < W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
      . . .
      . . .
      . . .
```
[Try it online!](https://ethproductions.github.io/cubix/?code=dSouJHMuISguMDFJXjxXJU5XITs8LDs7cStwQE9wdXM=&input=MTA=&speed=2000)
# Notes
* Works with inputs up to and including 170, higher inputs result in an infinite loop, because their factorial yields the `Infinity` number (technically speaking, its a non-writable, non-enumerable and non-configurable property of the window object).
* Accuracy is lost for inputs 19 and up, because numbers higher than 253 (= 9 007 199 254 740 992) cannot be accurately stored in JavaScript.
# Explanation
This program consists of two loops. The first calculates the factorial of the input, the other splits the result into its digits and adds those together. Then the sum is printed, and the program finishes.
## Start
First, we need to prepare the stack. For that part, we use the first three instructions. The IP starts on the fourth line, pointing east. The stack is empty.
```
      . . .
      . . .
      . . .
0 1 I . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .
```
We will keep the sum at the very bottom of the stack, so we need to start with `0` being the sum by storing that on the bottom of the stack. Then we need to push a `1`, because the input will initially be multiplied by the number before it. If this were zero, the factorial would always yield zero as well. Lastly we read the input as an integer.
Now, the stack is `[0, 1, input]` and the IP is at the fourth line, the fourth column, pointing east.
### Factorial loop
This is a simple loop that multiplies the top two elements of the stack (the result of the previous loop and the input - n, and then decrements the input. It breaks when the input reaches 0. The `$` instruction causes the IP to skip the `u`-turn. The loop is the following part of the cube. The IP starts on the fourth line, fourth column.
```
      u * .
      $ s .
      ! ( .
. . . ^ < . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .
```
Because of the `^` character, the IP starts moving north immediately. Then the `u` turns the IP around and moves it one to the right. At the bottom, there's another arrow: `<` points the IP back into the `^`. The stack starts as `[previousresult, input-n]`, where `n` is the number of iterations. The following characters are executed in the loop:
```
*s(
*   # Multiply the top two items
    #   Stack: [previousresult, input-n, newresult]
 s  # Swap the top two items
    #   Stack: [previousresult, newresult, input-n]
  ( # Decrement the top item
    #   Stack: [previousresult, newresult, input-n-1]
```
Then the top of the stack (decreased input) is checked against `0` by the `!` instruction, and if it is `0`, the `u` character is skipped.
### Sum the digits
The IP wraps around the cube, ending up on the very last character on the fourth line, initially pointing west. The following loop consists of pretty much all remaining characters:
```
      . . .
      . . .
      . . .
. . . . . W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
      . . .
      . . .
      . . .
```
The loop first deletes the top item from the stack (which is either `10` or `0`), and then checks what is left of the result of the factorial. If that has been decreased to `0`, the bottom of the stack (the sum) is printed and the program stops. Otherwise, the following instructions get executed (stack starts as `[oldsum, ..., factorial]`):
```
N%p+q;;,s;
N          # Push 10
           #   Stack: [oldsum, ..., factorial, 10]
 %         # Push factorial % 10
           #   Stack: [oldsum, ..., factorial, 10, factorial % 10]
  p        # Take the sum to the top
           #   Stack: [..., factorial, 10, factorial % 10, oldsum]
   +       # Add top items together
           #   Stack: [..., factorial, 10, factorial % 10, oldsum, newsum]
    q      # Send that to the bottom
           #   Stack: [newsum, ..., factorial, 10, factorial % 10, oldsum]
     ;;    # Delete top two items
           #   Stack: [newsum, ..., factorial, 10]
       ,   # Integer divide top two items
           #   Stack: [newsum, ..., factorial, 10, factorial/10]
        s; # Delete the second item
           #   Stack: [newsum, ..., factorial, factorial/10]
```
And the loop starts again, until `factorial/10` equals 0.
[Answer]
## C, 47 bytes
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
```
usage:
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
main() {
  printf("answer: %d\n",f(10,1));
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes
```
ḟẹ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO@Q937dT@/9/SwvR/FAA "Brachylog – Try It Online")
Same "algorithm" as the [v1 answer](https://codegolf.stackexchange.com/a/100832/8774) by @Fatalize, just with better encoding. 
[Answer]
# Python, 57 bytes
```
import math
lambda n:sum(map(int,str(math.factorial(n))))
```
[**Try it online**](https://repl.it/E6TZ)
[Answer]
## Batch, 112 bytes
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
:g
@set/at+=f%%10,f/=10
@if %f% gtr 0 goto g
@echo %t%
```
Conveniently `set/a` works on a variable's current value, so it works normally inside a loop. Only works up to 12 due to the limitations of Batch's integer type, so in theory I could save a byte by assuming `f<1e9`:
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
@for /l %%i in (1,1,9)do @set/at+=f%%10,f/=10
@echo %t%
```
But that way lies madness... I might as well hard-code the list in that case (97 bytes):
```
@call:l %1 1 1 2 6 6 3 9 9 9 27 27 36 27
@exit/b
:l
@for /l %%i in (1,1,%1)do @shift
@echo %2
```
[Answer]
## JavaScript (ES6), 50 bytes
```
f=(n,m=1,t=0)=>n?f(n-1,n*m):m?f(n,m/10|0,t+m%10):t
```
Only works up to `n=22` due to floating-point accuracy limitations.
[Answer]
# [Befunge 93](http://esolangs.org/wiki/Befunge), ~~56~~ 54 bytes
Saved 2 bytes do to using get instead of quotes. This let me shift the top 2 lines over 1, reducing unnecessary white space.
[Try it online!](http://befunge-98.tryitonline.net/#code=JiM6PF92IzotMQo6IFwqJDw6X14jCmc6OnY-OTErJSswMApfdiM8XnAwMDwvKzE5CkA-JCQu&input=MTA)
```
&#:<_v#:-1
: \*$<:_^#
g::v>91+%+00
_v#<^p00</+19
@>$$.
```
Explanation:
```
&#:<                Gets an integer input (n), and reverses flow direction
&#:< _v#:-1         Pushes n through 0 onto the stack (descending order)
:  \*$<:_^#         Throws the 0 away and multiplies all the remaining numbers together
(reorganized to better show program flow):
vp00< /+19 _v#<    Stores the factorial at cell (0, 0). Pushes 3 of whatever's in
> 91+%+ 00g ::^    cell (0, 0). Pops a, and stores a / 10 at (0, 0),
                   and adds a % 10 to the sum.
@>$$.              Simply discards 2 unneeded 0s and prints the sum.
```
[Answer]
# Javascript ES6 - 61 54 Bytes
```
n=>eval(`for(j of''+(a=_=>!_||_*a(~-_))(n,t=0))t-=-j`)
```
**EDIT:** Thank you Hedi and ETHproductions for shaving off 7 bytes. I'll have to remember that t-=-j trick.
[Answer]
# [AHK](https://autohotkey.com/), 60 bytes
```
a=1
Loop,%1%
a*=A_Index
Loop,Parse,a
b+=A_LoopField
Send,%b%
```
AutoHotkey doesn't have a built-in factorial function and the loop functions have long names for their built-in variables. The first loop is the factorial and the second is adding the digits together.
[Answer]
# J, ~~12~~ 11 bytes
*Saved 1 byte thanks to cole!*
```
1#.10#.inv!
```
This simply applies sum (`1#.`) to the digits (using inverse `inv` of base conversion `#.` with a base of `10`) of the factorial (`!`) of the argument.
## Test cases
Note: the last two test cases are bigints, as marked by a trailing `x`.
```
   f=:10#.inv!
   (,. f"0) 10 19 469x 985x
 10    27
 19    45
469  4140
985 10053
```
]