| Bytes | Lang | Time | Link |
|---|---|---|---|
| 054 | Desmos | 250801T225828Z | ErikDaPa |
| 057 | AWK | 250801T194804Z | xrs |
| 055 | Swift 6 | 250429T181817Z | macOSist |
| 075 | Tcl | 180423T152305Z | sergiol |
| 001 | Thunno 2 S | 230623T155257Z | The Thon |
| 024 | TIBasic | 221122T030441Z | Youserna |
| nan | Fig | 221122T062427Z | south |
| 021 | Juby | 221117T224853Z | Jordan |
| 019 | q | 221118T013826Z | cillianr |
| 002 | Vyxal | 210316T115821Z | lyxal |
| 030 | Scala | 201222T182552Z | user |
| 043 | Perl 5 MListUtil=sum MMathBigInt p | 201222T165242Z | Xcali |
| 008 | APL Dyalog Extended | 201220T173236Z | Kamila S |
| 003 | Brachylog v2 | 180727T234451Z | Sundar R |
| 070 | Java 10 | 180727T185641Z | Jakob |
| 010 | K ngn/k | 180708T213356Z | mkst |
| 009 | MATL | 180707T140639Z | Sundar R |
| 066 | Python 3 | 180707T114852Z | aryaman |
| 016 | Pari/GP | 180113T150825Z | alephalp |
| 003 | Japt | 180222T151737Z | Shaggy |
| 002 | Pyt | 171227T204246Z | mudkip20 |
| 065 | Clojure | 161215T173104Z | NikoNyrh |
| 047 | C | 180113T043232Z | user8420 |
| 025 | Julia 0.6 | 180104T183803Z | gggg |
| 011 | J | 161125T180229Z | Conor O& |
| 060 | AHK | 170426T162339Z | Engineer |
| 032 | Cubix | 170425T203832Z | Luke |
| 654 | Javascript ES6 54 Bytes | 161123T193706Z | Marcus D |
| 073 | Lithp | 161124T220039Z | Andrakis |
| 053 | R | 161123T152830Z | Billywob |
| 021 | Perl 6 | 161124T194906Z | Brad Gil |
| 116 | C# | 161123T233311Z | Pete Ard |
| 112 | Java8 112 Chars | 161124T144117Z | Nati |
| nan | F# | 161124T123433Z | CodeMonk |
| 054 | Befunge 93 | 161123T182101Z | MercyBea |
| 022 | Wonder | 161124T004841Z | Mama Fun |
| 050 | JavaScript ES6 | 161123T204203Z | Neil |
| 112 | Batch | 161123T203649Z | Neil |
| 038 | Ruby | 161123T143526Z | TuxCraft |
| 058 | C | 161123T192344Z | teksturi |
| 061 | Groovy | 161123T194536Z | Magic Oc |
| 033 | bash seq | 161123T144146Z | Adam |
| 003 | Pyke | 161123T171034Z | Blue |
| 006 | Pyth | 161123T145301Z | BookOwl |
| 030 | Octave | 161123T155849Z | Stewie G |
| 058 | C++11 | 161123T154603Z | Karl Nap |
| 044 | PHP | 161123T154752Z | user5917 |
| 054 | Python | 161123T152723Z | Jonathan |
| 040 | Haskell | 161123T144910Z | nimi |
| 041 | Q/KDB+ 41 Bytes | 161123T152743Z | Adam J |
| 060 | C | 161123T152017Z | Karl Nap |
| 004 | Pushy | 161123T152017Z | FlipTack |
| 051 | Ruby | 161123T143616Z | G B |
| 008 | CJam | 161123T145958Z | Martin E |
| 008 | Pip | 161123T145354Z | Emigna |
| 148 | Java 7 | 161123T144008Z | jacksone |
| 057 | Python | 161123T144819Z | mbomb007 |
| 005 | Brachylog | 161123T144319Z | Fatalize |
| 003 | 05AB1E | 161123T143408Z | Magic Oc |
| 003 | Jelly | 161123T142511Z | Martin E |
| 021 | Mathematica | 161123T142202Z | Martin 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
Tcl, 75 bytes
proc S n {time {append p *[incr i]} $n
expr [join [split [expr 1$p] ""] +]}
proc S n {proc F n {expr $n?($n)*\[F $n-1]:1}
expr [join [split [F $n] ""] +]}
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
Sra
a # (num) range [1, a]
r # (lst) product
S # (num) digit sum
J-uby, 21 bytes
:+|:/&:*|:digits|:sum
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
‼∑
A very literal interpretation of the challenge: sum_of_digits_of(factorial(input))
Scala, 30 bytes
1.to(_).product+""map(_-48)sum
And a 34 byte solution without postfix syntax:
x=>(""+1.to(x).product:\0)(_+_-48)
Perl 5 -MList::Util=sum -MMath::BigInt -p, 43 bytes
Supports arbitrarily large factorials.
$_=sum(Math::BigInt->new($_)->bfac()=~/./g)
Perl 5 -MList::Util=sum,product -p, 27 bytes
Cannot handle extremely large factorials due to overflow.
$_=product 1..$_;$_=sum/./g
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/⍳))))
Brachylog (v2), 3 bytes
ḟẹ+
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();}
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));}
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))
;
}
MATL, 9 bytes
:p[]&V!Us
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:
(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!
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)))
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 .
. . . . . . . . . . . .
. . .
. . .
. . .
Notes
- Works with inputs up to and including 170, higher inputs result in an infinite loop, because their factorial yields the
Infinitynumber (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.
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.
&#:<_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:+}
- -3 bytes thanks to Martin Ender
- -5 bytes thanks to G B
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
Pyth, 7 6 bytes
Thanks to @Kade for saving me a byte
sj.!QT
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).
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:+
Explanation
r e# Read input.
i e# Convert to integer.
m! e# Take factorial.
Ab e# Get decimal digits.
:+ e# 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;
Brachylog, 5 bytes
$!@e+
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
Mathematica, 21 bytes
Tr@IntegerDigits[#!]&