Factorial digit sum

25

4

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!

george

Posted 2016-11-23T14:14:05.517

Reputation: 1 495

What's the maximum input number to expect? With 32-bit integers in R this challenge can't be solved accurately past n>21 – Billywob – 2016-11-23T15:22:16.123

1@Billywob For R then you will only need to go to 20. I shall edit question to reflect this – george – 2016-11-23T15:23:56.190

Answers

13

05AB1E, 3 bytes

!SO

Try it online!

!   Factorial.
 S  Push characters separately.
  O Sum.

Magic Octopus Urn

Posted 2016-11-23T14:14:05.517

Reputation: 19 422

11

Jelly, 3 bytes

!DS

Try it online!

Does what you expect:

!    Factorial.
 D   Decimal digits.
  S  Sum.

Martin Ender

Posted 2016-11-23T14:14:05.517

Reputation: 184 808

8

Mathematica, 21 bytes

Tr@IntegerDigits[#!]&

Martin Ender

Posted 2016-11-23T14:14:05.517

Reputation: 184 808

4came here to type these exact characters. – Michael Stern – 2016-11-23T18:19:08.227

Why [#!] and not @#!? (Mathematica noob) – Cyoce – 2016-11-24T02:07:06.007

1@Cyoce because @ has higher precedence than !. – Martin Ender – 2016-11-24T06:41:57.800

7

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

TuxCrafting

Posted 2016-11-23T14:14:05.517

Reputation: 4 547

1The old boring eval way: ->n{eval"#{(1..n).reduce:*}".chars*?+}. – manatwork – 2016-11-23T19:56:45.467

7

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

Karl Napf

Posted 2016-11-23T14:14:05.517

Reputation: 4 131

6

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

BookOwl

Posted 2016-11-23T14:14:05.517

Reputation: 291

110 is assigned to a variable T, so you can make this sj.!QT :) – Kade – 2016-11-23T16:23:47.880

OK, thanks! I'll add it – BookOwl – 2016-11-23T16:31:54.787

Nice! ssM`.! does the job too, also in 6 bytes.

– hakr14 – 2018-04-23T16:35:39.487

5

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!

nimi

Posted 2016-11-23T14:14:05.517

Reputation: 34 639

f x=sum$read.pure<$>(show$product[1..x]) saves a byte – Angs – 2016-11-23T14:58:09.247

5

Python, 54 bytes

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

repl.it

Jonathan Allan

Posted 2016-11-23T14:14:05.517

Reputation: 67 804

I just came up with a slightly worse version of this that looks way too similar for it to be a separate answer. Bravo – osuka_ – 2018-01-04T04:41:51.257

5

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

Billywob

Posted 2016-11-23T14:14:05.517

Reputation: 3 363

1I 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. – Jonathan Carroll – 2016-11-24T02:34:58.243

2how about prod(1:scan())? – MickyT – 2016-11-24T19:17:22.257

1also as.double should suffice – MickyT – 2016-11-24T19:31:36.987

@MickyT Thanks! Updated. – Billywob – 2016-11-24T20:17:19.313

strtoi works as a shorter replacement as.double, I think. – Giuseppe – 2018-01-04T18:44:38.450

A bit of playing around with splitting digits gives me this now sum(utf8ToInt(c(prod(1:scan()),''))-48) for 39 – MickyT – 2018-04-23T20:03:11.967

4

Pip, 8 bytes

$+$*++,a

Try it online!

Explanation

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

Emigna

Posted 2016-11-23T14:14:05.517

Reputation: 50 798

Sorry, I actually managed to post an 05AB1E answer before you ;). – Magic Octopus Urn – 2016-11-23T19:49:18.237

2@carusocomputing: Hehe. Got me the opportunity to look into a new language :) – Emigna – 2016-11-23T20:36:27.420

1I think you're the first one besides me to use Pip for a non-polyglot code golf answer. :D – DLosc – 2016-12-22T23:32:33.923

4

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.

Martin Ender

Posted 2016-11-23T14:14:05.517

Reputation: 184 808

3

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.

G B

Posted 2016-11-23T14:14:05.517

Reputation: 11 099

3

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;

jacksonecac

Posted 2016-11-23T14:14:05.517

Reputation: 2 584

@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? – jacksonecac – 2016-11-23T15:34:51.537

3

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

Adam

Posted 2016-11-23T14:14:05.517

Reputation: 591

fold -1 saves a byte. – Digital Trauma – 2016-11-23T17:45:01.590

@DigitalTrauma corrected! thanks – Adam – 2016-11-23T17:47:47.443

3

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

Fatalize

Posted 2016-11-23T14:14:05.517

Reputation: 32 976

3

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

FlipTack

Posted 2016-11-23T14:14:05.517

Reputation: 13 242

3

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

Stewie Griffin

Posted 2016-11-23T14:14:05.517

Reputation: 43 471

3

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

teksturi

Posted 2016-11-23T14:14:05.517

Reputation: 39

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? – JollyJoker – 2016-11-25T15:24:11.283

Return eats much. I try that of course. Maybe someone can do it at least i couldn't get that work – teksturi – 2016-12-01T12:47:44.343

1

you could accept two arguments to save a few bytes: https://codegolf.stackexchange.com/a/153132/77415

– user84207 – 2018-01-13T06:17:52.743

3

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
}

Brad Gilbert b2gills

Posted 2016-11-23T14:14:05.517

Reputation: 12 713

Congrats, you got answer no. 101010! – RudolfJelin – 2016-11-26T22:55:23.320

@RudolfL.Jelínek That's nothing, on StackOverflow, and Meta.StackExchange I am user number 1337

– Brad Gilbert b2gills – 2016-11-26T23:15:02.617

3

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.

Luke

Posted 2016-11-23T14:14:05.517

Reputation: 4 675

3

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

user84207

Posted 2016-11-23T14:14:05.517

Reputation: 171

2

Python, 57 bytes

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

Try it online

mbomb007

Posted 2016-11-23T14:14:05.517

Reputation: 21 944

Could you use back ticks instead of str? – nedla2004 – 2016-11-23T15:48:10.257

2@nedla2004 That would append an L once the factorial is big enough to become a long. – Kade – 2016-11-23T15:48:49.320

2

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.

MildlyMilquetoast

Posted 2016-11-23T14:14:05.517

Reputation: 2 907

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. – MildlyMilquetoast – 2016-11-23T22:50:53.377

Thanks! It looks like this code only works properly in the Befunge-98 version, probably because of the put method.

– MildlyMilquetoast – 2016-11-24T00:52:02.457

48 bytes which also handles 0 correctly – Jo King – 2018-01-15T04:27:49.643

2

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.

Marcus Dirr

Posted 2016-11-23T14:14:05.517

Reputation: 51

1Nice answer! You can save a couple bytes in various ways: n=>{a=_=>!_||_*a(~-_);t=0;for(j of''+a(n))t-=-j;return t} – ETHproductions – 2016-11-25T18:13:53.987

@ETHproductions Some more bytes can be saved with eval : n=>eval(\for(j of''+(a==>!||*a(~-))(n,t=0))t-=-j`)` – Hedi – 2016-11-25T22:52:04.330

@Hedi I know, I was taking it one step at a time :-) – ETHproductions – 2016-11-25T23:23:57.703

2

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

Neil

Posted 2016-11-23T14:14:05.517

Reputation: 95 035

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.

Neil

Posted 2016-11-23T14:14:05.517

Reputation: 95 035

2

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

Conor O'Brien

Posted 2016-11-23T14:14:05.517

Reputation: 36 228

You can use "."0": to get digits – Bolce Bussiere – 2018-01-04T02:09:05.967

11 bytes: 1#.,.&.":@! which requires extended precision for smaller cases too (unsure why). Also 11 bytes: 1#.10#.inv!. – cole – 2018-01-04T02:55:23.347

2

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.

Engineer Toast

Posted 2016-11-23T14:14:05.517

Reputation: 5 769

2

Brachylog (v2), 3 bytes

ḟẹ+

Try it online!

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

sundar - Reinstate Monica

Posted 2016-11-23T14:14:05.517

Reputation: 5 296

1

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

Karl Napf

Posted 2016-11-23T14:14:05.517

Reputation: 4 131

Do we define f (n) as int by default? – Mukul Kumar – 2016-11-25T14:09:18.423

@MukulKumar this is standard in C, if there is no type then int is assumed. – Karl Napf – 2016-11-25T17:14:09.803

1

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.

Adam J

Posted 2016-11-23T14:14:05.517

Reputation: 81

1

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

user59178

Posted 2016-11-23T14:14:05.517

Reputation: 1 007

1

Pyke, 3 bytes (old version)

SBs

Explanation:

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

Blue

Posted 2016-11-23T14:14:05.517

Reputation: 26 661

1

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.

Magic Octopus Urn

Posted 2016-11-23T14:14:05.517

Reputation: 19 422

1

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

Pete Arden

Posted 2016-11-23T14:14:05.517

Reputation: 1 151

You can compile to a Func<int, long> to save bytes, the for loop can be simplified to for (; i > 1;) and then set i = n outside the loop above and post decrement i in the loop i.e. f *= i--;. I think the ToList() isn't needed although I haven't tried it and you will need to add using System.Linq; into the byte count for the ForEach part – TheLethalCoder – 2016-11-24T15:53:14.100

int.Parse(c+"") can be replaced with c-30 I think... – TheLethalCoder – 2016-11-24T16:18:20.640

Its 48 not 30 I read the hex code by accident, also you can't remove the ToList, putting all of that together is 113 bytes including the 18 for the using statement: using System.Linq;n=>{long f=1;int s=0,i=n;for(;i>1;)f*=i--;f.ToString().ToList().ForEach(c=>s+=c-48);return s;}; – TheLethalCoder – 2016-11-24T16:27:57.957

@TheLethalCoder Thanks for the tips :) I've had another play around with it and saved 3 Bytes :) – Pete Arden – 2016-11-24T18:11:49.490

1

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.

Mama Fun Roll

Posted 2016-11-23T14:14:05.517

Reputation: 7 234

1

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.

CodeMonkey

Posted 2016-11-23T14:14:05.517

Reputation: 111

2Hi, and welcome to the site! Your answers are actually slightly better than you thought; unless it's vital to your program, you can remove the newline at the end of a file and save a byte that way. (You can produce the nicely formatted headings we use elsewhere by starting the heading with a # sign.) Also, I think F# has the function notation for creating an anonymous match block (e.g. you can use let rec s=function|0L rather than let rec s x=match x with|0L); that should help you get your code a bit shorter. – None – 2016-11-24T13:22:54.027

Thank you, it's the first time I saw the anonymous match. I select the functions in my code editor which told me 81 characters selected without the newline. I'm wondering if I got it wrong. – CodeMonkey – 2016-11-24T13:35:00.937

1

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.

Andrakis

Posted 2016-11-23T14:14:05.517

Reputation: 361

1

Japt, 3 bytes

Êìx

Try it

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

Shaggy

Posted 2016-11-23T14:14:05.517

Reputation: 24 623

1

Tcl, 78 bytes

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

Try it online!

sergiol

Posted 2016-11-23T14:14:05.517

Reputation: 3 055

1

K (ngn/k), 10 bytes

Solution:

+/10\*/1+!

Try it online!

Explanation to follow.

streetster

Posted 2016-11-23T14:14:05.517

Reputation: 3 635

0

Java8 - 112 Chars

(First time here...)

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

Nati

Posted 2016-11-23T14:14:05.517

Reputation: 101

0

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

NikoNyrh

Posted 2016-11-23T14:14:05.517

Reputation: 2 361

0

Pyt, 3 2 bytes

Explanation:

        Implicit input
!       Get factorial
 Ś      Sum the digits

Try it online!

mudkip201

Posted 2016-11-23T14:14:05.517

Reputation: 833

0

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!

gggg

Posted 2016-11-23T14:14:05.517

Reputation: 1 715

0

Pari/GP, 16 bytes

n->sumdigits(n!)

Try it online!

alephalpha

Posted 2016-11-23T14:14:05.517

Reputation: 23 988

0

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!

aryaman

Posted 2016-11-23T14:14:05.517

Reputation: 1

1Welcome to PPCG! – Jonathan Frech – 2018-07-07T13:02:54.900

0

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.

sundar - Reinstate Monica

Posted 2016-11-23T14:14:05.517

Reputation: 5 296

0

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

Jakob

Posted 2016-11-23T14:14:05.517

Reputation: 2 428