# Factorial digit sum

## 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 thanks to Martin Ender

This is , so shortest code in characters wins!

• What's the maximum input number to expect? With 32-bit integers in R this challenge can't be solved accurately past n>21 Nov 23, 2016 at 15:22
• @Billywob For R then you will only need to go to 20. I shall edit question to reflect this Nov 23, 2016 at 15:23
• Great challenge! Nov 21, 2022 at 22:50

# 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[#!]&

• came here to type these exact characters. Nov 23, 2016 at 18:19
• Why [#!] and not @#!? (Mathematica noob) Nov 24, 2016 at 2:07
• @Cyoce because @ has higher precedence than !. Nov 24, 2016 at 6:41

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


## Ruby, 636153 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
• The old boring eval way: ->n{eval"#{(1..n).reduce:*}".chars*?+}. Nov 23, 2016 at 19:56

# 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

• 10 is assigned to a variable T, so you can make this sj.!QT :)
Nov 23, 2016 at 16:23
• OK, thanks! I'll add it Nov 23, 2016 at 16:31
• Nice! ssM.! does the job too, also in 6 bytes. Apr 23, 2018 at 16:35

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! • f x=sum$read.pure<$>(show$product[1..x]) saves a byte
– Angs
Nov 23, 2016 at 14:58

# Python, 54 bytes

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


repl.it

• I just came up with a slightly worse version of this that looks way too similar for it to be a separate answer. Bravo Jan 4, 2018 at 4:41

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

• I reached the exact same answer as you did, then found a 1-byte gain on c(x,"") vs paste(x): sum(as.integer(el(strsplit(c(factorial(scan()),""),"")))). Coerces the factorial result to character and strsplit returns it as a second list, so el still works and extracts the first list elements. Nov 24, 2016 at 2:34
• how about prod(1:scan())? Nov 24, 2016 at 19:17
• also as.double  should suffice Nov 24, 2016 at 19:31
• @MickyT Thanks! Updated. Nov 24, 2016 at 20:17
• strtoi works as a shorter replacement as.double, I think. Jan 4, 2018 at 18:44

# Pip, 8 bytes

$+$*++,a


Try it online!

Explanation

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

• Sorry, I actually managed to post an 05AB1E answer before you ;). Nov 23, 2016 at 19:49
• @carusocomputing: Hehe. Got me the opportunity to look into a new language :) Nov 23, 2016 at 20:36
• I think you're the first one besides me to use Pip for a non-polyglot code golf answer. :D Dec 22, 2016 at 23:32

## 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.


# 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!

• -3 Dec 22, 2020 at 9:39
• 1⊥10⊤! should work I guess (since you're using Extended). That said, the 8 byter works without Extended. Dec 22, 2020 at 12:26
• @Bubbler I was interested mostly in stock Dyalog APL-only solutions. I'll change it to Dyalog Unicode soon-ish Dec 22, 2020 at 12:30

# 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


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

• @EyalLev There is no limit specified in the question. How are you expecting long to handle a factorial that equates to larger than 9,223,372,036,854,775,807? Nov 23, 2016 at 15:34

# 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.

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

• fold -1 saves a byte. Nov 23, 2016 at 17:45
• @DigitalTrauma corrected! thanks
Nov 23, 2016 at 17:47

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

• Nice idea, but I don't quite understand why it wouldn't be shorter to use one function to return the factorial and another to calculate the digit sum, like a(b(10)). Is the word "return" too long for that to work? Nov 25, 2016 at 15:24
• Return eats much. I try that of course. Maybe someone can do it at least i couldn't get that work Dec 1, 2016 at 12:47
• you could accept two arguments to save a few bytes: codegolf.stackexchange.com/a/153132/77415 Jan 13, 2018 at 6:17

# 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 }  • Congrats, you got answer no. 101010! Nov 26, 2016 at 22:55 • @RudolfL.Jelínek That's nothing, on StackOverflow, and Meta.StackExchange I am user number 1337 Nov 26, 2016 at 23:15 # 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 • 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. ## 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)); }  # Brachylog (v2), 3 bytes ḟẹ+  Try it online! Same "algorithm" as the v1 answer by @Fatalize, just with better encoding. # Python, 57 bytes import math lambda n:sum(map(int,str(math.factorial(n))))  Try it online • Could you use back ticks instead of str? Nov 23, 2016 at 15:48 • @nedla2004 That would append an L once the factorial is big enough to become a long. – Kade Nov 23, 2016 at 15:48 ## 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  ## 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. # 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.

• You are correct. I'm working on a new version. FYI, I'm using quickster.com, because others that I found didn't treat  correctly when there was only one # in the stack. Nov 23, 2016 at 22:50
• Thanks! It looks like this code only works properly in the Befunge-98 version, probably because of the put method. Nov 24, 2016 at 0:52
• 48 bytes which also handles 0 correctly
– Jo King
Jan 15, 2018 at 4:27

# 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.

• Nice answer! You can save a couple bytes in various ways: n=>{a=_=>!_||_*a(~-_);t=0;for(j of''+a(n))t-=-j;return t} Nov 25, 2016 at 18:13
• @ETHproductions Some more bytes can be saved with eval : n=>eval(for(j of''+(a=_=>!_||_*a(~-_))(n,t=0))t-=-j)
– Hedi
Nov 25, 2016 at 22:52
• @Hedi I know, I was taking it one step at a time :-) Nov 25, 2016 at 23:23

# 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.

# 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

• You can use "."0": to get digits Jan 4, 2018 at 2:09
• 11 bytes: 1#.,.&.":@! which requires extended precision for smaller cases too (unsure why). Also 11 bytes: 1#.10#.inv!`.
– cole
Jan 4, 2018 at 2:55