g | x | w | all
Bytes Lang Time Link
054Desmos250801T225828ZErikDaPa
057AWK250801T194804Zxrs
055Swift 6250429T181817ZmacOSist
075Tcl180423T152305Zsergiol
001Thunno 2 S230623T155257ZThe Thon
024TIBasic221122T030441ZYouserna
nanFig221122T062427Zsouth
021Juby221117T224853ZJordan
019q221118T013826Zcillianr
002Vyxal210316T115821Zlyxal
030Scala201222T182552Zuser
043Perl 5 MListUtil=sum MMathBigInt p201222T165242ZXcali
008APL Dyalog Extended201220T173236ZKamila S
003Brachylog v2180727T234451ZSundar R
070Java 10180727T185641ZJakob
010K ngn/k180708T213356Zmkst
009MATL180707T140639ZSundar R
066Python 3180707T114852Zaryaman
016Pari/GP180113T150825Zalephalp
003Japt180222T151737ZShaggy
002Pyt171227T204246Zmudkip20
065Clojure161215T173104ZNikoNyrh
047C180113T043232Zuser8420
025Julia 0.6180104T183803Zgggg
011J161125T180229ZConor O&
060AHK170426T162339ZEngineer
032Cubix170425T203832ZLuke
654Javascript ES6 54 Bytes161123T193706ZMarcus D
073Lithp161124T220039ZAndrakis
053R161123T152830ZBillywob
021Perl 6161124T194906ZBrad Gil
116C#161123T233311ZPete Ard
112Java8 112 Chars161124T144117ZNati
nanF#161124T123433ZCodeMonk
054Befunge 93161123T182101ZMercyBea
022Wonder161124T004841ZMama Fun
050JavaScript ES6161123T204203ZNeil
112Batch161123T203649ZNeil
038Ruby161123T143526ZTuxCraft
058C161123T192344Zteksturi
061Groovy161123T194536ZMagic Oc
033bash seq161123T144146ZAdam
003Pyke161123T171034ZBlue
006Pyth161123T145301ZBookOwl
030Octave161123T155849ZStewie G
058C++11161123T154603ZKarl Nap
044PHP161123T154752Zuser5917
054Python161123T152723ZJonathan
040Haskell161123T144910Znimi
041Q/KDB+ 41 Bytes161123T152743ZAdam J
060C161123T152017ZKarl Nap
004Pushy161123T152017ZFlipTack
051Ruby161123T143616ZG B
008CJam161123T145958ZMartin E
008Pip161123T145354ZEmigna
148Java 7161123T144008Zjacksone
057Python161123T144819Zmbomb007
005Brachylog161123T144319ZFatalize
00305AB1E161123T143408ZMagic Oc
003Jelly161123T142511ZMartin E
021Mathematica161123T142202ZMartin E

Desmos, 54 bytes

Big numbers in Desmos become inaccurate so out of the examples only 10 produces the right result.

f(x)=mod(floor(x!/10^{[floor(log(x!))...0]}),10).total

Try this online!

AWK, 57 bytes

{for(x=1;i++<$1;)x*=i;for(;j++<split(x,a,X);)y+=a[j]}$0=y

Attempt This Online!

Swift 6, 55 bytes

{"\((1...$0).reduce(1,*))".reduce(0){$0+Int("\($1)")!}}

Try it on SwiftFiddle!

Tcl, 75 bytes

proc S n {time {append p *[incr i]} $n
expr [join [split [expr 1$p] ""] +]}

Try it online!


# [Tcl], 78 bytes
proc S n {proc F n {expr $n?($n)*\[F $n-1]:1}
expr [join [split [F $n] ""] +]}

Try it online!

Thunno 2 S, 1 byte

w

Attempt This Online!

Thunno 2, 2 bytes

wS

Attempt This Online!

TI-Basic, 24 bytes (non-competing)

sum(10fPart(.1seq(int(Ans!/₁₀^(I)),I,0,int(log(Ans!

Only works for nonnegative integers up to 18, inclusive, and works up to 20 if you round to the nearest multiple of 9 when the input is greater than 5.

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes

Sra

Try it online!

Sra
  a  # (num) range [1, a]
 r   # (lst) product
S    # (num) digit sum

J-uby, 21 bytes

:+|:/&:*|:digits|:sum

Attempt This Online!

Explanation

:+ | :/ & :* | :digits | :sum

:+ |                           # Range 1..n, then
     :/ & :* |                 # Reduce with product, then
               :digits | :sum  # Sum digits

q, 19 bytes

sum 10 vs prd 1+til

k, 11 bytes

+/10\:*/1+!

prd 1+til generate the factorial of input

10 vs convert factorial to digits

Vyxal, 2 bytes

‼∑

Try it Online!

A very literal interpretation of the challenge: sum_of_digits_of(factorial(input))

Scala, 30 bytes

1.to(_).product+""map(_-48)sum

Try it online!

And a 34 byte solution without postfix syntax:

x=>(""+1.to(x).product:\0)(_+_-48)

Try it in Scastie

Perl 5 -MList::Util=sum -MMath::BigInt -p, 43 bytes

Supports arbitrarily large factorials.

$_=sum(Math::BigInt->new($_)->bfac()=~/./g)

Try it online!

Perl 5 -MList::Util=sum,product -p, 27 bytes

Cannot handle extremely large factorials due to overflow.

$_=product 1..$_;$_=sum/./g

Try it online!

APL (Dyalog 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!

Brachylog (v2), 3 bytes

ḟẹ+

Try it online!

Same "algorithm" as the v1 answer by @Fatalize, just with better encoding.

Java 10, 70 bytes

A lambda from long to int. Breaks for input over 20.

n->{var f=n;while(n>1)f*=--n;return(f+"").chars().map(c->c-48).sum();}

Try It Online

Java 10, 163 bytes

Fully arbitrary precision. A lambda from BigInteger to BigInteger.

n->{var i=n;var f=n;while(n.compareTo(n.ONE)>0)f=f.multiply(n=n.subtract(n.ONE));return(f+"").chars().mapToObj(c->i.valueOf(c-48)).reduce(n.ZERO,(a,b)->a.add(b));}

Try It Online

Ungolfed

n -> {
    var i = n;
    var f = n;
    while (n.compareTo(n.ONE) > 0)
        f = f.multiply(n = n.subtract(n.ONE));
    return (f + "").chars()
        .mapToObj(c -> i.valueOf(c - 48))
        .reduce(n.ZERO, (a, b) -> a.add(b))
    ;
}

K (ngn/k), 10 bytes

Solution:

+/10\*/1+!

Try it online!

Explanation to follow.

MATL, 9 bytes

:p[]&V!Us

Try it online!

MATL port of Stewie Griffin's Octave answer. Works up to n=22, same as the Octave and R answers.

:p - factorial.
[]&V - string representation of the number, fully expanded (without the []&, larger numbers use the scientific notation which won't do for our purposes).
!U transpose and convert back to numbers, getting individual digits.
s - sum those digits.

The []& part can be removed for -3 bytes, but then the range is further limited to only work up to 17, instead of 22.

I could stretch the input range to 23 with a couple of tricks, but that costs an additional 20 bytes:

:1w5X2Y%"@*t10\~?10/]][]&V!Us

(basically, use the uint64 data type instead of the usual double, multiply by each number upto the given number, but divide away 10 whenever our product is divisible by it (since trailing zeros add nothing to the digit sum).)

That seems to be as far as we can go with MATLAB/MATL without doing an ad-hoc implementation of bignum in the program.

Python 3, 66 bytes

import math;print(sum(map(int,str(math.factorial(int(input()))))))

It gets factorial of number, splits it into an array, then prints it!

Pari/GP, 16 bytes

n->sumdigits(n!)

Try it online!

Japt, 3 bytes

Êìx

Try it

Get the factorial, split to a digit array and reduce by addition.

Pyt, 3 2 bytes

Explanation:

        Implicit input
!       Get factorial
 Ś      Sum the digits

Try it online!

Clojure, 65 bytes

(fn[i](apply +(map #(-(int %)48)(str(apply *(range 1(inc i)))))))

Straightforward, character \0 has integer value of 48.

Easier to follow steps:

(defn f [i] (->> i inc (range 1) (apply *) str (map #(- (int %) (int \0)) (apply +)))

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));
}

Julia 0.6, 25 bytes

Julia functions are generic across input types, and generate optimized code for each combination of input types. This function works with machine sized integers or arbitrary precision integers depending on the type of the argument. eg

f(10) = 27
f(50) = -97 # overflowed
f(big(50)) = 216 # no overflow, but slower due to use of BigInt
x->sum(digits(prod(1:x)))

Try it online!

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

AHK, 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.

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!

Notes

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.

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.

Lithp, 73 bytes

#N::((sum (map (split (+ "" (prod (seq 1 N))) "") #C::((- (asc C) 48)))))

I'm not sure if I should be counting import calls. Here is how you would use the above snippet:

(
    (import "lists")
    (def f #N::((sum (map (split (+ "" (prod (seq 1 N))) "") #C::((- (asc C) 48))))))
    (print (f 10))
)

It works by calculating the factorial using prod/1, converts it to a string by doing (+ "" value), splits and maps the string to get the numeric value of each number (ASCII code - 48.) Lastly, we sum/1 the resulting list.

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()))),""))))

Perl 6, 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
}

C#, 119 116 Bytes

Edit: Saved 3 Bytes thanks to @TheLethalCoder

Golfed:

long F(int n){long f=1;int s=0;for(;n>1;)f*=n--;foreach(var c in f.ToString().ToList())s+=int.Parse(c+"");return s;}

Ungolfed:

public long F(int n)
{
  long f = 1;
  int s = 0;
  for (; n > 1;)
    f *= n--;
  foreach (var c in f.ToString().ToList())
    s += int.Parse(c + "");
  return s;
}

Tried both a long and an Int64 and it won't take higher than n=20, ultimately went with long because it is shorter...

Testing:

  Console.WriteLine(new DigitalSumFactorial().F(10));
  //27
  Console.WriteLine(new DigitalSumFactorial().F(19));
  //45
  Console.WriteLine(new DigitalSumFactorial().F(20));
  //54

Java8 - 112 Chars

(First time here...)

String.valueOf(LongStream.rangeClosed(2,i).reduce(1,(a,b)->a*b)).chars().map(Character::getNumericValue).sum();

F#, 80 bytes (74bytes for 32bit integer)

let rec s=function|0L->0L|y->y%10L+s(y/10L)
let g x={1L..x}|>Seq.fold (*) 1L|>s

F#, 98 bytes (96bytes for 32bit integer)

let f x=([1L..x]|>List.fold (*) 1L).ToString().ToCharArray()|>Array.fold (fun a c-> a+int(c)-48) 0

Test with

f 10L
g 10L

Thanks to ais523 for the anonymous match function and formatting help.

Befunge 93, 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!

&#:<_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.

Wonder, 22 bytes

@sum <>""prod rng1+1#0

This only works for inputs <= 21.

Usage:

(@sum <>""prod rng1+1#0)10

Explanation

Increment argument, tail-exclusive range from 1 to result, product, split over empty string, and sum.

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.

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

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:+}

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;}

Groovy, 61 bytes

{"${(1..it).inject{i,r->i*r}}".collect{0.parseInt(it)}.sum()​}​

Groovy doesn't even have factorial built-ins.

"${(1..it).inject{i,r->i*r}}" - Compute factorial as string.

.collect{0.parseInt(it)} - Turn the string into an array of integers.

.sum()​ - Sum 'em.

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

Pyke, 3 bytes (old version)

SBs

Explanation:

SB  -  product(range(1, input+1))
  s - digit_sum(^)

Pyth, 7 6 bytes

Thanks to @Kade for saving me a byte

sj.!QT

Try it online!

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

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 :)

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.

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);
}

PHP, 44 bytes

<?=array_sum(str_split(gmp_fact($argv[1])));

Well it's not clever, but it works. That said it turned out better than I thought (I thought I'd need to use gmp_strval() too).

Python, 54 bytes

f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))

repl.it

Haskell, 41 40 bytes

f x=sum$read.pure<$>(show$product[1..x])

Usage example: f 985 -> 10053.

Make a list from 1to 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!

Q/KDB+ 41 Bytes

sum{:"I"$string x}over'string prd 1+til n

Breakdown:

string prd 1+til n

Get the product from 1 to n

{:"I"$string x}

Function that accepts a string x and returns it converted to an integer.

over'

Iterate over the argument to it's right to the function on the left, passing each item in individually.

sum

Sum up the numbers output by the function at the end.

C, 63 60 bytes

-3 byte for do...while loop.

i;f(n){i=n;while(--n)i*=n;do n+=i%10;while(i/=10);return n;}

Ungolfed and usage:

i;
f(n){
 i=n;
 while(--n)
  i*=n;
 do
  n+=i%10;
 while(i/=10);
 return n;
}

main() {
 printf("%d\n",f(10));
}

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

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.

CJam, 8 bytes

rim!Ab:+

Try it online!

Explanation

r   e# Read input.
i   e# Convert to integer.
m!  e# Take factorial.
Ab  e# Get decimal digits.
:+  e# Sum.

Pip, 8 bytes

$+$*++,a

Try it online!

Explanation

      ,a    # range
    ++      # increment
  $*        # fold multiplication
$+          # fold sum

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;

Python, 57 bytes

import math
lambda n:sum(map(int,str(math.factorial(n))))

Try it online

Brachylog, 5 bytes

$!@e+

Try it online!

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

05AB1E, 3 bytes

!SO

Try it online!

!   Factorial.
 S  Push characters separately.
  O Sum.

Jelly, 3 bytes

!DS

Try it online!

Does what you expect:

!    Factorial.
 D   Decimal digits.
  S  Sum.

Mathematica, 21 bytes

Tr@IntegerDigits[#!]&