| Bytes | Lang | Time | Link |
|---|---|---|---|
| 076 | Tcl | 180421T161921Z | sergiol |
| 078 | old problem JavaScript Node.js | 180421T051114Z | l4m2 |
| 008 | CJam | 180424T155911Z | vazt |
| 098 | Ceylon | 180423T202715Z | Paŭlo Eb |
| 135 | Java 10 | 180423T070946Z | Kevin Cr |
| 036 | Bash + GNU utilities | 180421T020319Z | Digital |
| 051 | Python 2 | 180422T171415Z | lynn |
| 075 | Python | 180422T130908Z | Adi219 |
| 004 | Stax | 180421T190917Z | Khuldrae |
| 042 | Octave with Symbolic Package | 180421T153206Z | Luis Men |
| 052 | Python 2 | 180421T014538Z | Chas Bro |
| 038 | Haskell | 180421T033351Z | user7946 |
| 002 | Pyt | 180421T144244Z | mudkip20 |
| 066 | R + gmp | 180421T140048Z | Giuseppe |
| nan | 180421T134333Z | Brad Gil | |
| 033 | Ruby | 180421T122533Z | benj2240 |
| 003 | Husk | 180421T120709Z | Fyr |
| 107 | C gcc | 180421T115802Z | user2027 |
| 054 | Elixir | 180421T103746Z | Okx |
| 007 | Charcoal | 180421T102428Z | Neil |
| 002 | Neim | 180421T102340Z | Okx |
| 011 | J | 180421T084502Z | Galen Iv |
| 003 | 05AB1E | 180421T080548Z | Emigna |
| 016 | Pari/GP | 180421T052204Z | alephalp |
| 024 | Wolfram Language Mathematica | 180421T022254Z | Pavel |
| 011 | Attache | 180421T020230Z | Conor O& |
| 003 | Jelly | 180421T014247Z | Arnauld |
Tcl, 76 bytes
proc S n {time {append f *[incr i]} $n
expr [join [split [expr 1*$f] ""] +]}
proc S n {proc F n {expr $n?($n)*\[F $n-1]:1}
expr [join [split [F $n] ""] +]}
(old problem) JavaScript (Node.js), 99 94 92 88 86 83 80 78 bytes
f=(x,t=[...21+Array(999)])=>x?f(s=x-1,t.map(d=>-s+(s+=(t=~~d*x+t/10|0)%10))):s
well, first language without large number support
Thank Arnauld for 4 bytes
f = (x, t = ['2', '1', ...','.repeat(998)]) => // init x, t=1
x ?
f( // recursive x':=x-1, t'=t*x
s = x-1, // s init to 0 when x==1, in next recursion just return
t.map (
b = // init b to NaN
d =>
-s + ( // to return the added value
s+= ( // -s + (s + k) == k
b=
~~d*x+b/10 | 0
// ~~d converts ',' to 0
// b is initally NaN, after first iteration
// it's zero, then the last digit sum result with carry
) % 10
)
)
)
:
s // the sum from x==1
CJam, 11 8 bytes
there is in fact a better way to get a list of digits
lim!Ab:+
Explanation:
li input, convert to integer
m! factorial
Ab convert to array of digits in base 10
:+ sum
Original solution:
lim!`1/:i:+
Explanation:
li input converted to integer
m! factorial
` convert to string
1/ split into pieces of length 1
:i convert back to integer
:+ sum
Ceylon, 98 bytes
import ceylon.whole{l=one}Integer q(Integer n)=>sum({0,*product({l,*(l:n)}).string*.offset('0')});
Explanation:
This is quite long, because we need to convince the compiler that we are not doing bogus stuff.
import ceylon.whole { l = one } // 1
Integer q(Integer n) => // 2
sum({0,*product({l,*(l:n)}).string *.offset('0')});
// | | | | '3' || | | | | |||
// | | | '--4-----'| | | 7 | |||
// | | '----5------------' '-6--' '--8------'||
// | | '----------------9---------------------'||
// | '----------------10-------------------------'|
// '------------------------11----------------------'
- Import the value
onefrom the packageceylon.whole, and give it locally the namel(small L, not the digit1– though I choose this alias for its similarity to 1). (This alias import costs two bytes here, but saves two bytes for each of the two usages). - Define a function
qfromIntegertoInteger, which maps each parameternto the result of the following expression (calculated in steps 3 to 11). Top-level functions always need a type declaration. For local ones we could replace the return type byfunction, which wouldn't have saved anything here. (For inline functions, we sometimes can omit both types and the keyword, if they can be inferred from context.) - This is a short syntax for
measure(one, n), which returns either the empty sequence[]ifnis non-positive, or aRange<Whole>starting fromoneand having sizen(i.e. all numbers from 1 to n, assuming n is a positive integer). Type:[]|Range<Whole>, which is a subtype of{Whole*}(possibly empty iterable of Whole). - This is an iterable enumeration, with
oneas the first element and then all the elements ofone:n(the*here expands the iterable). This has type{Whole+}, and has the only purpose to make sure the compiler knows it is non-empty. We could have used[...]instead of{...}for a tuple enumeration (which is non-lazy). No difference here apart from performance. We could have written this(l:n).follow(l), but that is longer. - Calculate the product of all those numbers, type
Whole.productneeds a non-empty iterable as a parameter to work (as the product of nothing is not defineable in a type-independent way). - Get the string representation of the result of step 5. (The
.stringattribute exists for all classes, andWholeimplements it in the expected way, using decimal digits.) – typeString, which is also a{Character*}(possibly empty iterable of characters). - The
*.operator for iterables applies the the following attribute or method call to each element of the iterable and collects the result in a sequence. It can be seen as syntactic sugar for.collect(c => c.offset('0')). This is non-lazily evaluated, there is also.map(...)which is lazy. - The
offsetmethod ofCharacterjust calculates the difference between the unicode code points, returning anInteger. This takes advantage of the fact that the ten decimal digits are sequential starting with0in ASCII (and thus unicode). - This whole thing has now type
[Integer*](possibly empty sequence of integers – because the string is possibly empty for the compiler). - Same trick again as step 4, we make it an
{Integer+}(nonempty iterable) by prepending a0(which has no effect on the following sum). - Sum it all up.
Java 10, 135 bytes
n->{var r=java.math.BigInteger.ONE;for(;!n.equals(r.ZERO);n=n.subtract(r.ONE))r=r.multiply(n);return(r+"").chars().map(c->c-48).sum();}
Explanation:
n->{ // Method with BigInteger parameter and integer return-type
var r=java.math.BigInteger.ONE;
// BigInteger, starting at 1
for(;!n.equals(r.ZERO); // Loop as long as `n` is not 0 yet
n=n.subtract(r.ONE)) // After every iteration: subtract 1 from `n`
r=r.multiply(n); // Multiply `r` by `n`
return(r+"").chars() // Loop over the characters of `r`
.map(c->c-48) // Convert them to digits
.sum();} // And return the sum of those digits
Python 2, 51 bytes
f=lambda L,p=1:0**L*sum(map(eval,`p`))or f(L-1,p*L)
We'd like to write map(int,`p`), but since repr(p) might have a trailing L, that won't work.
Ordinarily, we'd resort to map(int,str(p)) and lose three bytes.
Here, can we name our counting-down variable L, and write map(eval,`p`). Since L is 0 when we compute the result, the digit sum is unaffected.
Python, 75 bytes
import math
print(sum(map(int,list(str(math.factorial(int(input())))))))
Stax, 4 bytes
║▼⌡è
Run and debug it at staxlang.xyz!
Unpacked (5 bytes) and explanation
|FE|+
|F Implicit input. Factorial.
E Array of decimal digits.
|+ Sum of list. Implicit print.
Octave with Symbolic Package, 43 42 bytes
@(s)sum(char(sym(['factorial(' s 41]))-48)
Anonymous function that takes the input as a string and outputs a nubmer.
Python 2, 52 54 52 bytes
f=lambda n,r=1:1/n*sum(map(int,str(r)))or f(n-1,n*r)
-2 bytes thx to Kirill L.
Haskell, 42 40 38 bytes
f n=sum[read[d]|d<-show$product[1..n]]
Thanks to @Laikoni for saving 2 bytes with list comprehension.
R + gmp, 66 bytes
sum(strtoi(el(strsplit(paste(gamma(gmp::as.bigz(scan())+1)),""))))
gmp is one of the several BigInteger packages available on CRAN.
Perl 6, 21 bytes
{[*](2..$_).comb.sum}
Expanded:
{ # bare block lambda with implicit parameter 「$_」
[*]( # reduce using &infix:« * »
2 .. $_ # Range starting at 2 (slight optimization over 1)
).comb # split the result into digits
.sum # find the sum of those digits
}
C (gcc), 107 bytes
f(x){int a[999]={1},i,c;
for(;x;--x)for(c=i=0;i<999;)c=(a[i]=a[i]*x+c)/10,a[i++]%=10;
for(;i--;)x+=a[i];
i=x;}
Elixir, 54 bytes
fn n->Enum.sum Integer.digits Enum.reduce 1..n,&*/2end
Ungolfed:
def sum_factorial(n) do
# factorial
Enum.reduce(1..n, fn(x, acc) -> x * acc end)
# sum digits
|> Integer.digits
|> Enum.sum
Charcoal, 7 bytes
IΣΠ…¹⊕N
Try it online! Link is to verbose version of code. Explanation:
N Input as a number
⊕ Increment
¹ Literal 1
… Range
Π Product
Σ Sum (of digits)
I Cast to string
Implicitly print
InclusiveRange(1, InputNumber()) also works but the explanation is prettier this way.
Neim, 2 bytes
𝐓𝐬
Explanation: Factorial 𝐓; sum 𝐬.
This outgolfs 3-byte answers as the sum command is able to implicitly convert to a list.
J, 13 11bytes
1#.,.&.":@!
Explanation:
! calculate the factorial
@ and
,.&.": convert it to a list of digits (convert to string ":, ravel ,. and convert each char back to number)
1#. find their sum by base-1 conversion
Attache, 11 bytes
Sum@List@`!
Sums the List of digits in the factorial (!) of the input. Anonymous function.
Jelly, 3 bytes
!DS
!DS - main link, taking an integer e.g. 9
! - factorial --> 362880
D - convert to decimal --> [3,6,2,8,8,0]
S - sum of list --> 27