[Question]
      [
It's Christmas everybody, and here's a code-golf challenge to celebrate. You need to make a program to print out a present. Specifically, the words "Merry Christmas". BUT, there is a catch: this program must only work if it is the 25th of December. If the code is run on any other day, then the program should crash.
This is Code-Golf, so the answer with the least amount of bytes wins.
Merry Christmas!

[Answer]
## Pyke, 21 bytes
```
.dↄґ6C65h*325q/Al
```
[Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916C65h%2a325q%2FAl)
```
     C65h*        -   multiply the day by the (current month + 1)
          325q    -  ^ == 325
    6         /   - 6 / ^
.dↄґ              -  load "merry christmas"
               Al - ^.capwords()
```
Or 18 bytes noncompetitive.
```
.dↄґ6Cs6Y1q/Al
```
Exactly the same except for this section:
```
Cs6Y1q
C      -    get_time()
 s6    -   add 1 week
   Y   -  get day of the year
    1q - ^ == 1
```
[Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916Cs6Y1q%2FAl)
[Answer]
# JavaScript, ~~55~~ ~~53~~ 46 bytes
Note: this has only been tested in Google Chrome, program may behave differently from browser to browser (or device to device)
*2 bytes saved thanks to @ConorO'Brien*
*7 bytes saved thanks to @ETHProductions*
```
alert(/c 25/.test(Date())?"Merry Christmas":a)
```
Exits with `Uncaught ReferenceError: a is not defined` if the date is not `Dec 25`. I'm not really sure if this counts as crashing
```
alert(/c 25/.test(Date())?"Merry Christmas":a)
```
[Answer]
# Python 3, ~~66~~ 63 bytes
Thanks to ideas from JavaScript / ES answers here I managed to squeeze some bytes. Index a dictionary - non-existent keys will raise a `KeyError`. The following code works in local time zone
```
import time;print({1:'Merry Christmas'}['c 25'in time.ctime()])
```
The output format for `ctime` isn't locale-dependent - the format is always ~ `'Sun Dec 25 19:23:05 2016'`. Since only in December does the 3-letter abbreviation end with `c`, it is safe to use `'c 25'in time.ctime()` here.
---
**Previous version:**
This works in UTC time zone. For local time zone one needs to `s/gm/local` for 3 more bytes. For Python 2, one can remove parentheses from `print` for 65 bytes.
```
import time;print({(12,25):'Merry Christmas'}[time.gmtime()[1:3]])
```
The construct throws `KeyError` on other dates:
```
>>> import time;print({(1,1):'Happy New Year'}[time.gmtime()[1:3]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: (12, 25)
```
[Answer]
# PHP, ~~39~~ 38 bytes, not competing (doesn´t crash)
```
<?=date(md)-1225?"":"Merry Christmas";
```
or
```
<?date(md)-1225?die:0?>Merry Christmas
```
or
```
<?=["Merry Christmas"][date(md)-1225];
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~68~~ ~~67~~ 65 bytes
-1 with thanks to @muddyfish
Thanks to @AnttiHaapala for the idea that saved another couple.
```
import time;print['Merry Christmas'][(12,25)!=time.gmtime()[1:3]]
```
[Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbal1QlJlXEq3um1pUVKngnFGUWVySm1isHhutYWikY2SqqWgLUqaXnguiNDSjDa2MY2P//wcA "Python 2 – TIO Nexus")
Throws an IndexError if not 25th Dec.
Non-competing version for 59 bytes as it only works for non Leap years (uses day of year which is 360 this year but 361 in leap years)
```
import time;print['Merry Christmas'][360!=time.gmtime()[7]]
```
[Answer]
## R, 52 61 58 bytes
```
`if`(format(Sys.Date(),"%m%d")=="1225","Merry Christmas",)
```
If the current date is not the 25th of December then an error is returned because no third argument is supplied to `if`.
Edit: Fixed a silly error
[Answer]
My first time around here... Started with the best language ever for this job:
# Java, ~~200~~ ~~188~~ bytes (thanks to @Daniel Gray), 186 bytes removing "ln" from print.
```
import java.util.*;public class a{public static void main(String[]r){Calendar c=Calendar.getInstance();if(!(c.get(2)==11&&c.get(5)==25)){int i=1/0;}System.out.print("Merry Christmas");}}
```
[Try it here!](https://www.compilejava.net/)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~34~~ 33 bytes
```
'Merry Christmas'IHh&Z'5U12h=?}Yl
```
This works in [current version (19.7.0)](https://github.com/lmendo/MATL/releases/tag/19.7.0) of the language. To cause the error, the following code exploits the fact that the logarithm of a string gives an error (this may change in future versions).
[Try it online!](https://tio.run/nexus/matl#@6/um1pUVKngnFGUWVySm1is7umRoRalbhpqaJRha18bmfP/PwA "MATL – TIO Nexus")
### Explanation
```
'Merry Christmas'  % Push this string
IHh                % Push 3, then 2, concatenate: gives array [3 2]
&Z'                % Get 3rd and 2nd outputs of clock vector: current day and month
5U12h              % Push 5, square, push 12, concatenate: gives [25 12]
=                  % Compare if corresponding entries are equal in the two arrays
?                  % If all entries are equal: do nothing
}                  % Else
  Yl               %   Logarithm. Gives an error when applied on a string
                   % End (implicit). Display (implicit)
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 48 bytes
```
~left$$|(_D,5)=@12-25||?@Merry Christmas|\?a(12)
```
Explanation:
```
~             IF
left$$|(_D,5) the date string starts with
=@12-25|      the string "12-25"
|             THEN
[[email protected]](/cdn-cgi/l/email-protection)|     PRINT "Merry Christmas"
\             ELSE
?a(12)        Print the twelfth index of an undefined array.
              Since there are only 11 elements in undefined arrays, this
              results in an index-out-of-bounds error.
The the IF statement is auto-closed by QBIC.
```
This assumes American `MM-DD` date notation. This would be shorter if I'd finally make a Substring function in QBIC.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 21 bytes
Saved 11 bytes thanks to Adnan's string compression :) .
```
1žfže‚12D·>‚Q÷”ÞÙŒÎ”×
```
## Explanation
```
 žfže‚                Push [current month, current day]
      12D·>‚          Push [12, 25]
            Q         Push tmp = 1 if the two arrays are equal, tmp = 0 otherwise
1            ÷        Evaluate x = 1/tmp. If tmp = 0 a division by 0 exception is thrown
              ”ÞÙŒÎ”× Implicitly display "Merry Christmas" x times
```
[Try it online!](https://tio.run/nexus/05ab1e#@294dF/a0X2pjxpmGRq5HNpuB2QEHt7@qGHu4XmHZx6ddLgPxJz@/z8A "05AB1E – TIO Nexus")
I did what came to mind first, so there may be better approaches for this one. But PPCG deserves a Merry Christmas in 05AB1E as well ;) .
[Answer]
# C# / CS Script ~~106~~ ~~100~~ 99 bytes
99 byte solution
```
using System;int i;Console.WriteLine(DateTime.Now.ToString("dM")=="2512"?"Merry Christmas":i/0+"");
```
[Try it here!](https://dotnetfiddle.net/VNCSxf)
100 byte solution (prefer this one... a bit different)
```
using System;int i;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":i/0+"");
```
Explained:
```
using System;
int i;
// if today plus 7 days is the first day of the year, then it's xmas!
Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1
    ? "Merry Christmas"
// otherwise divide i by 0
    : i/0+"");
```
`DateTime.Now.AddDays(7).DayOfYear==1` is one byte shorter than `DateTime.Now.ToString("ddMM")=="2512"` but 1 byte longer than `DateTime.Now.ToString("dM")=="2512"`
[Answer]
# C#/CS Script, 96 Bytes, Mostly Plagiarized from Erresen
```
using System;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":1/0+"");
```
Deletes the `int i` declaration in favor of hard coding the division. I would leave this as a comment but don't have the reputation.
[Answer]
# bash + Unix utilities, ~~51~~ ~~49~~ 47 bytes
```
((`date +%m%d`-1225))&&${};echo Merry Christmas
```
\*Thanks to @KenY-N for pointing out that the quotes in the echo can be removed, and to @IporSircer for reducing the condition size by 2 bytes.
[Answer]
# Groovy, 57 bytes
```
print new Date().format("Md")=="1225"?"Merry Christmas":b
```
Crashes on dates other than 25.12. with `groovy.lang.MissingPropertyException` because `b` is not defined.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked/), 42 bytes
[Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)
```
('Merry Christmas')'MMDD'date'1225'=¬#out
```
This creates a single-element array containing namely `'Merry Christmas!'`. After, it puts the date into a string with the month followed by the day. It checks for equality with `'1225'` (Christmas), inverts it with `¬`, then gets that member from the preceding array. If it isn't Christmas, this will error with an index error. Otherwise, it prints `Merry Christmas`. (Change the date in the string to see how it works on other days.)
[Answer]
## Batch, 66 bytes
```
@echo off
if %date:~0,5%==25/12 echo Merry Christmas&exit/b
if
```
The trailing newline is significant, as it causes parsing of the `if` statement to fail. You may need to tweak the date check to match your local date format.
[Answer]
# Python 2, ~~69 77~~ 75 or ~~72~~ 70 Bytes
```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
else:1/0
```
If it doesn't matter if it exits with an error when it is Christmas, then:
```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
1/0
```
EDIT:
Thanks @Flp.Tkc for pointing out that I needed to raise an error
-2 Bytes from @Max for pointing out about removing colons from the strftime function
[Answer]
# CJam, 28
```
et[C25]#1="Merry Christmas"/
```
[Try it online](http://cjam.aditsu.net/#code=et%5BC25%5D%231%3D%22Merry%20Christmas%22%2F)
**Explanation:**
```
et                   push an array of current [year month day hour ...]
[C25]                push the array [12 25] (C=12)
#                    find the position of the 2nd array within the first one
1=                   compare it with 1, resulting in 1 for 1 and 0 otherwise
"Merry Christmas"/   split "Merry Christmas" into pieces of that length
                      (it crashes if the length is 0)
                     at the end, all the pieces are concatenated
                      and printed automatically
```
[Answer]
## C#.NET, ~~180~~ ~~172~~ 171 bytes
*Saved 8 bytes thanks to Kritixi Lithos*
*Saved 1 byte thanks to Kritixi Lithos, again ;)*
```
namespace System{class P{static void Main(string[] args){var d=DateTime.Today;if(d.Day==25)if(d.Month>11){Console.Write("Merry Christmas!");return;}throw new Exception();}}}
```
Alternative, ungolfed variant:
```
namespace System //In System, so we don't have to use system.
{
    class Program
    {
        static void Main(string[] args) //Main function.
        {
            var d = DateTime.Today; //Get Today.
            if (d.Day == 25) if (d.Month == 12) //Day has to be 25th, Month has to be 12nd.
                {
                    Console.Write("Merry Christmas!"); return; //Prints.
                }
            throw new NotChristmasException(); //Errors/Crashes the program.
        }
    }
    class NotChristmasException : Exception { } //Holiday exception, hooray!
}
```
[Answer]
# Mathematica, 46 bytes
```
If[Today[[1,2;;]]=={12,25},"Merry Christmas!"]
```
[Answer]
# Common Lisp, 140
```
(let((m(multiple-value-list(decode-universal-time(get-universal-time)))))(if(and(eq(nth 3 m)25)(eq(nth 4 m)12))(write"Merry Christmas")(c)))
```
Crashes with undefined function if the date isn't right.
[Answer]
## awk, 29 bytes (+ length("Merry xmas"))
```
v=1225==strftime("%m%d")||1/0
```
Running it:
```
$ echo Merry xmas | awk 'v=1225==strftime("%m%d")||1/0'
awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted
```
Season greeting is piped to `awk`. `strftime` returns month+day (for example `1226`) and if it matches `1225` `$0` record gets outputed. Result of comparison `1225==1226` is placed to `v` var which is used to divide 1 if the date comparison fails.
[Answer]
## Haskell, 116
Crashes with "Non-exhaustive patterns in function f" if it's not Christmas.
```
import Data.Time
f(_,12,25)="Merry Christmas"
main=getZonedTime>>=print.f.toGregorian.localDay.zonedTimeToLocalTime
```
Unfortunately, there's no function that allows you to just immediately get the time in a useful format, so most of this is converting the date formats.
[Answer]
# C#, ~~122~~ 104 bytes
18 bytes saved, thanks to @raznagul
```
using System;i=>{if(DateTime.Now.AddDays(7).DayOfYear==1)Console.Write("Merry Christmas");else{i/=0;};};
```
It adds 7 days to the current day, and checks if it is the first day of the year, if yes, it displays "Merry Christmas", otherwise it divides by zero.
[Answer]
## Ruby, 69 bytes
```
if Time.now.strftime("%j")=="360";puts "Merry Christmas";else 0/0;end
```
Works in 2016. Doesn't differentiate between normal and leap years, may need to be adjusted for non-leap years.
[Answer]
# ForceLang, 180 bytes
```
set s datetime.toDateString datetime.now()
set t "Dec 25"
def c s.charAt i
def d t.charAt i
set i -1
label 1
set i 1+i
if i=6
 io.write "Merry Christmas!"
 exit()
if c=d
goto 1
z.z
```
(Remember that `datetime.toDateString` is locale-dependent, so this may not work depending on your locale)
[Answer]
# C#, 90 bytes
```
using System;Console.Write(new[]{"Merry Christmas"}[DateTime.Now.AddDays(7).DayOfYear-1]);
```
Throws IndexOutOfRangeException if it's not christmas.
[Try it here!](https://dotnetfiddle.net/6wbSVV)
[Answer]
# bash command line, ~~45~~ ~~48~~ 49 48 bytes
```
date +%m%d|grep -q 1225&&echo Merry Christmas||!-
date +%m%d|grep -q 1225||!-;echo Merry Christmas
```
Similar to [Mitchell Spector's](https://codegolf.stackexchange.com/a/104609/63348), but use `grep` in silent mode to check for a match, then `&&` will ensure that it only prints on success, and the `||` causes it to look up history with `!-`, which gives me this:
```
-bash: !-: event not found
```
And it stops execution as `!- ; echo foo` demonstrates. The `bash` documentation says that `!-n` refers to the current command minus `n`, so perhaps it is being interpreted as `!-0`, which gives an identical (and non-localised) error message.
]


[Question]
      [
We had a [prime factorization challenge](https://codegolf.stackexchange.com/q/1979/42545) a while ago, but that challenge is nearly six years old and barely meets our current requirements, so I believe it's time for a new one.
## Challenge
Write a program or function that takes as input an integer greater than 1 and outputs or returns a list of its prime factors.
## Rules
* Input and output may be given by any standard method and in any standard format.
* Duplicate factors must be included in the output.
* The output may be in any order.
* The input will not be less than 2 or more than 231 - 1.
* Built-ins are allowed, but including a non-builtin solution is encouraged.
## Test cases
```
2 -> 2
3 -> 3
4 -> 2, 2
6 -> 2, 3
8 -> 2, 2, 2
12 -> 2, 2, 3
255 -> 3, 5, 17
256 -> 2, 2, 2, 2, 2, 2, 2, 2
1001 -> 7, 11, 13
223092870 -> 2, 3, 5, 7, 11, 13, 17, 19, 23
2147483646 -> 2, 3, 3, 7, 11, 31, 151, 331
2147483647 -> 2147483647
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.**

[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
f=lambda n,k=2:n/k*[0]and(f(n,k+1),[k]+f(n/k,k))[n%k<1]
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk21rZJWnn60VbRCbmJeikaYBFNI21NSJzo7VBnL0s3WyNTWj81SzbQxj/xcUZeaVKKRpGJmaav4HAA "Python 2 – TIO Nexus")
[Answer]
# [Pyth](https://pyth.herokuapp.com/?code=P&input=2147483646&debug=0), 1 byte
```
P
```
I like Pyth's chances in this challenge.
[Answer]
## Python 2, 53 bytes
```
f=lambda n,i=2:n/i*[f]and[f(n,i+1),[i]+f(n/i)][n%i<1]
```
Tries each potential divisor `i` in turn. If `i` is a divisor, prepends it and restarts with `n/i`. Else, tries the next-highest divisor. Because divisors are checked in increasing order, only the prime ones are found.
As a program, for 55 bytes:
```
n=input();i=2
while~-n:
 if n%i:i+=1
 else:n/=i;print i
```
[Answer]
# Mathematica, ~~38~~ 30 bytes
Thanks @MartinEnder for 8 bytes!
```
Join@@Table@@@FactorInteger@#&
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
(2%)
n%1=[]
n%m|mod m n<1=n:n%div m n|k<-n+1=k%m
```
[Try it online!](https://tio.run/##XY3BbsIwDIbvfgofqMREI9Vx2xREuPACHCdtHKpBt6pNmMa0C@zVlznVaNEkW/Zvf7/9Vp@7Y9@Hxj6HuU4ewCdkn/ZS3NWdDujQr8n6lU8O7VdU126t/IJsl7jg6tajxfeP1n/iDBukLCOAiwKNaoMaOBaGfFCpDMq/jqG6zeKY9KQYdFEMvhSLFMmILu/gfwHxZ1wbYUlS/Jqzpa5Mdns2HBr38abkUszCUm7yisu8nGAeYY6GIjZME2oGdFSgvsPPS9PXr@egHre73S8 "Haskell – Try It Online") Example usage: `(2%) 1001` yields `[7,11,13]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Æf
```
[Try it online!](https://tio.run/nexus/jelly#@3@4Le3/4fZHTWvc//830lEw1lEw0VEw01Gw0FEwBPKNTE1BBFDA0MDAEMg0MjawNLIwNwAyDU3MTSyMzUzMkNjmAA "Jelly – TIO Nexus")
[Answer]
# JavaScript (ES6), 44 bytes
```
f=(n,x=2)=>n-1?n%x?f(n,x+1):[x,...f(n/x)]:[]
```
Horribly inefficient due to the fact that it iterates from 2 up to every prime factor, including the last. You can cut the time complexity dramatically at the cost of 5 bytes:
```
f=(n,x=2)=>x*x>n?[n]:n%x?f(n,x+1):[x,...f(n/x,x)]
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~37~~ 32 bytes
```
vs(...<..1I>(!@)s)%?w;O,s(No;^;<
```
[Try it online!](https://tio.run/nexus/cubix#@19WrKGnp2ejp2foaaeh6KBZrKlqX27tr1Os4ZdvHWdt8/@/kZGxgaWRhbkBAA "Cubix – TIO Nexus") or [Watch it in action](http://ethproductions.github.io/cubix/?code=dnMoLi4uPC4uMUk+KCFAKXMpJT93O08scyhObzteOzw=&input=MTI=&speed=4).
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
Basically this checks all integers `2, 3, 4, 5, ...` for divisors of `n`. If we find one, we factor that out and repeat the process until we get to `1`.
```
f 1=[]
f n=(:)<*>f.div n$until((<1).mod n)(+1)2
```
[Try it online!](https://tio.run/##XY7BDoIwDIbvfYoeOIACoSswMMCLGA8kSFyEaRS9GJ8dNyJgTNas/9/v73aq7@dj141ji1TuD9CiLt2dV2yqNmzUE7Xz0IPqXLcgL@wvDWrP3ZInxr5WGku83pQe0MEWheAoF5mMAF4BCAwqFMD2Yogn5Rsj/XYM2exZm8SqGESSTDkfEx9JGp3@wH8HKIrIjqVhyZTJz1@ZH5sWLXO701RuwoalWMYZp3G6wrzAbAOJbZhWVE7ooiB4jx8 "Haskell – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 6 bytes
```
w`in`M
```
[Try it online!](https://tio.run/nexus/actually#@1@ekJmX4Pv/vwUA "Actually – TIO Nexus")
Explanation:
```
w`in`M
w       factor into primes and exponents
 `in`M  repeat each prime # of times equal to exponent
```
[Answer]
# J, 2 bytes
```
q:
```
~~Body must be at least 30 characters.~~
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Yf
```
[Try it online!](https://tio.run/nexus/matl#@x@Z9v@/kQkA "MATL – TIO Nexus")
Obligatory "boring built-in answer".
[Answer]
# Japt, 2 bytes
```
Uk
```
A built-in `k` used on the input `U`. Also refers to a country.
[Test it online!](http://ethproductions.github.io/japt/?v=master&code=VWs=&input=MTEwMTE=)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
ǐ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHkCIsIiIsIjIxNDc0ODM2NDYiXQ==)
Just the built-in. But that's boring, so
## [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 8 bytes
```
K~æ~Ǒ$ẋf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLfsOmfseRJOG6i2YiLCIiLCIyMTQ3NDgzNjQ2Il0=)
## Explained
```
ʀ~æ~Ǒ$ẋf
ʀ~æ      # From the all numbers in the range [0, input], keep only those that are prime
   ~Ǒ    # Without popping anything, get the multiplicity of each prime divisor - this leaves the stack as [divisors, multiplicities]
     $ẋ  # Swap the two items and repeat each divisor multiplicity times
       f # Flatten and output that
```
[Answer]
# [tone-deaf](https://github.com/kade-robertson/tone-deaf), 3 bytes
This language is quite young and not really ready for anything major yet, but it can do prime factorization:
```
A/D
```
This will wait for user input, and then output the list of prime factors.
[Answer]
# MATLAB, 6 bytes
I think this does not require any explanation.
```
factor
```
[Answer]
## Batch, 96 bytes
```
@set/an=%1,f=2,r=0
:l
@set/af+=!!r,r=n%%f
@if %r%==0 echo %f%&set/an/=f
@if %n% gtr 1 goto l
```
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 52 bytes
```
p=function(n,i=2)if(n>1)c(i[m<-!n%%i],p(n/i^m,i+!m))
```
[Try it online!](https://tio.run/##dZHxCoIwEMb/7ykuIthoktvUGWQvEhVhEw5yytTnt1liOQnuYPvuft/dmO1ri6W@Ffe8rWyT9XVWdCZvsTLEMMwExYKYE6c5wXN5DNZmu8ULq4nZ47VkuFuXlM49iKCwgeAkVnNZfmTpydHYzcAHkqniM@mXWWJc/FZ9VMTxuAeDmAFXi3oyM/fCnxWG/NOunBd3uZgnZHgQqQq/j3kPnvqHHVwenPmC5ZGKUplEyS8sJ1gOBvFwkPwfqkZ0ukMGxR2fDTw6DW3logoeWtdgdd7Zxn38qn8B "R – Try It Online")
Recursive function: overflows the stack limit and errors on TIO for the last test case.
---
# [R](https://www.r-project.org/), ~~59~~ 58 bytes
```
function(n,i=2)while(n>1)if(n%%i)i=i+1 else{show(i);n=n/i}
```
[Try it online!](https://tio.run/##dY/taoMwFIb/9yoOlIJhlplEjWWktzJcG9dDs2QkEX@MXbvTVmyNDHLgfD3ve@L6b4df6r2pT8E6L/umNaeA1iQmRclId0GtEnOkBJvE7HZIUOILBaW9@vEX2yVI3ow0r/i7VEoYgS3sj2yzbPN7m0ftfNpOIQbKeRIz1YNZY5Q9T2OUFcV0RwpFClSs5uVCPHqxV5bR@7oYtOgQKz/GswOrRPb4zM143h9vGOIwiK9Ymou84mVePsN8hvkoUIwJp5vtP6yY2LkGCWerPBgbQDlnXQofbYAOtYZQXxXUoK35hDDIQW3O4O0t93vbhv4P "R – Try It Online")
Non-recursive function: does not error for large primes, but will still take a very long time to run (and so times-out without erroring on TIO for the last test case anyway).
[Answer]
# [CellTail](https://github.com/mousetail/CellTail/blob/main/README.md), 166 bytes
```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;a&(_,_,_),N,N:1,a,N;_,(v,1),_:1,v,N;N,u,N:1,(u,2,u%2),N;
```
[Try the demo](https://mousetail.github.io/CellTail/#ST1DIE47Ck89TjsKI009NDA7CgpOLCh1LHUsXyksTjoxLCh1LDEpLCgwLDIpOygwLDIpLE4sTjoxLE4sTjtOLCh1LHYsMCksTjoxLCh2LDEpLCh1L3YsMiwodS92KSUyKTtOLCh1LHYsdyksTjoxLCh1LHYrMSx1JSh2KzEpKSxOO2EmKF8sXyxfKSxOLE46MSxhLE47XywodiwxKSxfOjEsdixOO04sdSxOOjEsKHUsMix1JTIpLE47)
## Explanation:
Base case, when we reach the end switch to a recursion resistant tuple and pass a message right to break it. Then the message right sends a 1 to prevent recursion when the tuple has broken.
```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;
```
We have found a factor, try again in the cell to the right with `(u/v)`
```
N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);
```
We have not found a factor, try another.
```
N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;
```
Copy 3-tuples from left to current
```
a&(_,_,_),N,N:1,a,N;
```
Break recursion resistant tuples. Hopefully the next step the value from the right will throw a 1 to break the recursion.
```
_,(v,1),_:1,v,N;
```
Base case, start with trying 2 as a factor.
```
N,u,N:1,(u,2,u%2),N;
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 19 bytes
```
factor|sed s/.*:.//
```
[Try it online!](https://tio.run/nexus/bash#@5@WmFySX1RTnJqiUKyvp2Wlp6///7@RqSkA "Bash – TIO Nexus")
[Answer]
## Pyke, 1 byte
```
P
```
[Try it here!](http://pyke.catbus.co.uk/?code=P&input=12)
Prime factors builtin.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 58 bytes
Not done golfing yet, but @MartinEnder should be able to destroy this anyway
Prints out factors space-separated, with a trailing space
Golfed:
```
2}\..}$?i6;>(<...=.\'/})."@...>%<..'':\}$"!>~\{=\)=\}&<.\\
```
Laid-out:
```
     2 } \ . .
    } $ ? i 6 ;
   > ( < . . . =
  . \ ' / } ) . "
 @ . . . > % < . .
  ' ' : \ } $ " !
   > ~ \ { = \ )
    = \ } & < .
     \ \ . . .
```
Explanation coming later.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Ò
```
[Try it online!](https://tio.run/nexus/05ab1e#@3940v//RoYm5iYWxmYmZgA "05AB1E – TIO Nexus")
[Answer]
# CJam, 2 bytes
```
mf
```
[cjam.aditsu.net/...](//cjam.aditsu.net#code=rimf%60&input=2147483646)
This is a function. Martin, it seems I was sleepy.
[Answer]
## C, 92 bytes
```
int p(int n){for(int i=2;i<n;i++)if(n%i==0)return printf("%d, ",i)+p(n/i);printf("%d\n",n);}
```
Ungolfed version:
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int prime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            printf("%d, ", i);
            return prime(number / i); //you can golf away a few bytes by returning the sum of your recursive function and the return of printf, which is an int
        }                             //this allow you to golf a few more bytes thanks to inline calls
    }
    printf("%d\n", number);
}
int main(int argc, char **argv) {
    prime(atoi(argv[1]));
}
```
[Answer]
# [Java (OpenJDK)](http://openjdk.java.net/), 259 bytes
```
import java.util.*;interface g{static void main(String[]z){int a=new Scanner(System.in).nextInt();int b=0;int[]l={};for(int i=2;i<=a;i++){for(;a%i<1;l[b-1]=i){l=Arrays.copyOf(l,b=l.length+1);a/=i;}}for(int i=0;i<b;i++)System.out.print(l[i]+(i<b-1?", ":""));}}
```
[Try it online!](https://tio.run/nexus/java-openjdk#RY5BT4QwEIX/SkNi0sputStZzZbGePTkgSPhMGDB2ZRCyuwqEn47gjHx9JL33nzzFmz7LhA7wxXkhdDJW42ebKihsqyZBgLCil07fGctoOcZBfRNXnyLae0xMN5@sqwC723g2TiQbSV6Ib39oldPXGw4Vpr7TfPCmWnWdRf45qI5aEwNaIxjMW2uhhtMlXZ5uVeFQTE58xICjIOsun58q7nblcZJZ31DH7ESGu4M6nn@J65/0vIX@Demu5Ds183EXY5FzNd4r56jHYtOUSTEerwsB5U8Jk8Px@T4Aw "Java (OpenJDK) – TIO Nexus")
[Answer]
# [PHP](https://php.net/), 51 bytes
```
for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i*print"$i ";
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbGysZP0/Lb9IQyXT1sja0EYl0VYNLGetqZKoqpJpr5KprW2lkqhvq5KpVVCUmVeipJKpANTzHwA "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
i;f(n){for(i=2;i<=n;)n%i?i++:printf("%d ",i,n/=i);}
```
[Try it online!](https://tio.run/##XY7LCsIwEEXX5itKoDClLSZp@tBY/RapNMzCWGpdlX57TEwEcXXuXM4MM5R6GKxFNYLJ1vExA/ZC4ak3KjMpXjDPj9OMZhmBpreEFliYfY@Z2qwGVycmIyvZ/Sjl2VmuVmTnbzpMr@UJlLq4EeJ37lc08NnTILyhoQqQAU1AF8CjI@r6G6LAGeOxEhU7iK5lceSylV3VyOZvbv0X9g0 "C (gcc) – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 19 bytes
```
IT1WP2K%ZB|:N,:M?t;
```
[Try it online!](https://tio.run/##XY1NCgIxDIX3PUU37io0Sf9mBhTciSguBMEDqAOCi3Hp3WtSnFaEhua9fC@5PR/XcbrnvD3B@Yi7xWXz7g@m369fQ0a9XGlUJB8pV5RhI3w7Umn2xAZsihR6X3JGe6Mhsg4/8N9TYC3IODILXJxHsh2maOdjZVGdy06ujsPMgosuUXChwVRhkoCXhqChsaBV5XrvAw "Gol><> – Try It Online")
## Explanation
```
IT                  < [n]     read input to n then mark cell (T)
  1WP     |         < [n m=2] from 2 onwards (m=1;while m:m++;)
     2K%ZB          < [n m+1] copy two elements, mod, break if n%m==0
           :N       < [n m] (< where n%m==0) print m with newline
             ,:M?t; < [n/m] (< new n)        divide, if not 1 redo from T else exit
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 1 [byte](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ḋ
```
Boring built-in answer
[Try it online!](https://tio.run/##K6gs@f//4Y7u//8NjY0B)
]


[Question]
      [
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.

---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/68666/edit).
Closed 2 years ago.
[Improve this question](/posts/68666/edit)
As a spin-off to [my challenge over at Puzzling](https://puzzling.stackexchange.com/questions/25039/10-9-8-7-6-5-4-3-2-1-2016), your goal is to output `2016`.
Rules:
* You must include the numbers `10 9 8 7 6 5 4 3 2 1` in that order. They can be used as individual integers or concatenated together (like `1098`), but the `10` may not be separated into `1` and `0` - no character(s) may be present between the digits. Note that, in some languages, `10` may not actually represent the integer literal `10`, which is acceptable.
* Your code must not contain any other numbers or pre-defined number variables or constants (so `T` in Pyth is not allowed, since it is a numeric constant).
* You must **calculate** `2016` using numerics. Simply outputting `2016` without performing any operations on the required numbers (for example, by decoding an encoded string consisting of only alphabetic characters) is not allowed. Outputting `2016` in pieces (such as `20`, then `16`) is also not allowed; you must have a single output consisting of the numeric value `2016`.
* The valid answer with the fewest bytes wins.

[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ ~~15~~ 14 bytes
```
109876:54+3_21
```
[Try it online!](http://jelly.tryitonline.net/#code=MTA5ODc2OjU0KzNfMjE&input=)
### How it works
```
109876:54+3_21
109876            Initialize the left argument as 109876.
      :54         Perform integer division by 54, yielding 2034.
         +3       Add 3, yielding 2037.
           _21    Subtract 21, yielding 2016.
```
[Answer]
# Hexagony, 61 bytes
Not gonna win, but I just wanted to do a challenge in Hexagony.
This uses a different method than other answers (much worse). It takes some factors of 2016 (2,3,6,7,8) and multiplies them all together.
Minified:
```
\109.8/7}_=\"6<}{>...$_5_4/*!@...../}3.."2\/="*=}<*...$1>"*"/
```
Unminified:
```
    \ 1 0 9 .
   8 / 7 } _ =
  \ " 6 < } { >
 . . . $ _ 5 _ 4
/ * ! @ . . . . .
 / } 3 . . " 2 \
  / = " * = } <
   * . . . $ 1
    > " * " /
```
Explanation coming soon;
[Answer]
# Pyth, 16 bytes
```
+/109876 54-3 21
```
Does integer division, then adds (3-21).
Try it [here](http://pyth.herokuapp.com/?code=%2B%2F109876+54-3+21&debug=0).
[Answer]
## TI-BASIC, ~~17~~ 15 bytes
```
int(109876/54-‚àö(321
```
This uses @nicael's method.
17 bytes:
```
10+9*8-7+654*3-21
```
[This solution](https://puzzling.stackexchange.com/a/25050/12917) from Puzzling can be directly translated into TI-BASIC.
[Answer]
# Japt, ~~17~~ 16 bytes
```
√Ç(109876/54-321q
```
~~I hate this 17. Probably will find another solution.~~ YAYZ.
Explanation:
* `321q` is a square root of 321.
* `~~` floors the number.
[Try it online!](http://ethproductions.github.io/japt?v=master&code=wigxMDk4NzYvNTQtMzIxcQ==&input=)
[Answer]
# Matlab / Octave, 23 bytes
```
(10-9+8-7)^(6-5+4)*3*21
```
[Try it online](http://ideone.com/cLWq29)
[Answer]
# bc, 14
```
109876/54+3-21
```
Nothing exciting here - borrows from other answers.
[Answer]
## Haskell, 31 bytes
```
[10,9*8*7+const 6 5..]!!4+3*2*1
```
Not the shortest, `10+9*8-7+654*3-21` like seen in other answers works in Haskell too, but something different.
This builds a list starting with `10` and `9*8*7+6 = 510`, so the offset is `500` for the following elements. The whole list is `[10,510,1010,1510,2010,2510 ...]`. We pick the `4th` element (index 0-based), i.e. `2010` and add `3*2*1 = 6`. Voil√†.
I use `const 6 5 = 6` to get rid of the `5` which is not needed.
[Answer]
# Python 2, 20 bytes
```
print 109876/54+3-21
```
Again, that same boring `2016.(740)`. Makes use of the fact that if you don't have a decimal number in your expression it returns an integer.
[Answer]
# [BotEngine](https://github.com/SuperJedi224/Bot-Engine), ~~42~~ ~~39~~ ~~36~~ 13x2=26
```
v109876543210
>ee   e@  eRP
```
[Answer]
# ><> (fish), 18 bytes
```
10987**r65r4*n;321
```
explaination:
multiplies 9 8 and 7 together to get 504, reverses the stack and reverses it again right before the 4 is added, then multiplies 504 and 4 to get 2016. Then prints the number and ends the program before the last 3 numbers (i could do it after too with no difference, if that matters rules-wise).
[Answer]
# [Math++](http://esolangs.org/wiki/Math%2B%2B), 17 bytes
```
_(109876/54)+3-21
```
Actually, this prints `2016.0`. But there's really no way to print the exact string `2016` in this language.
The 17-byte TI-BASIC solution would also work here.
[Answer]
# Polyglot, 17 Bytes
```
10+9*8-7+654*3-21
```
This code, first used in [Thomas Kwa's TI-BASIC answer](https://codegolf.stackexchange.com/a/68682/44713), also works in:
* AppleScript (full program)
* bc (full program)
* Math++ (expression or full program)
* Mathematica (function, therefore not valid)
* Powershell (full program)
* Japt (full program)
* ~~JavaScript (console input, therefore not valid)~~ Needs second verification
* ~~Perl 5 (function, therefore not valid).~~ Needs second verification
* Haskell (function, therefore not valid)
* Python REPL (expression, so REPL environment is needed to get the output)
[Answer]
# ùîºùïäùïÑùïöùïü 2, 15 chars / 17 bytes
```
109876/54+3-21‚çú
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&output=&code=109876%2F54%2B3-21%E2%8D%9C)`
Translates to `round(109876/54+3-21)`.
*Thanks to @Dennis for saving 2 bytes!*
[Answer]
# Java 7, 31 bytes
```
int c(){return 109876/54+3-21;}
```
Boring port from other answers, of which I believe [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/68687/52210) was the first.
[Answer]
# PHP, 27 bytes
```
<?=~~(109876/54+3-21);
```
(22 bytes) was too boring,
so I used 10 to 9 as separate numbers:
```
<?=10*(9-8+7-6),5+4-3+2<<1;
```
other solutions, mostly with small cheats:
```
30: <?=10**(9+8-7-6)/5+4*3+(2<<1);
30: <?=10*trim(9*8,7),6+5+4+3-2*1;
29: <?=10*trim(9*8,76),5*4-3-2+1;
31: <?=10*trim(9*8,765),4+(3*2<<1);
31: <?=10*trim(9*8,765),4*3+(2<<1);
32: <?=ceil(1098*76/54)+321+ord(~j);
33: <?=(10<<9)/876*543/M_PI*2-M_E&~1;
```
[Answer]
# [CJam](https://esolangs.org/wiki/CJam), 15 bytes
```
109876 54/3+21-
```
Another port from Dennis' answer that I suspect works for many stack-based languages except 05AB1E, which seems to be the only stack-based answer besides Forth, which needs several more bytes.
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), ~~28~~ 25 bytes
```
10+9*(8)7;^*6*5/4*3/2*A!1
```
---
### Explanation
```
10+9*                      ` perform 10*9 (leaves 90 at TOS)
     (8)7;^*               ` get rid of 8 and multiply the TOS by 7
            6*5/4*3/2*A    ` perform TOS*6/5*4/3*2 (leaves 2016 at TOS)
                       !   ` output the TOS
                        1  ` push 1 to the stack
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes
```
109876 54√∑3+21-
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MTA5ODc2IDU0w7czKzIxLQ&input=)
Port of Dennis' answer.
[Answer]
# Forth, 22 bytes
Same calculation seen in other answers.
```
109876 54 / 3 + 21 - .
```
[**Try it online**](https://repl.it/ElA3)
[Answer]
# C 37 bytes
```
main(){printf("%d",109876/54+3-21);}
```
Same theme as many present.
[Answer]
# VBA, 15 bytes
```
?109876\54+3-21
```
(calculation unashamedly stolen from [Dennis](https://codegolf.stackexchange.com/a/68687/5011))
[Answer]
# JavaScript (ES6), 21 bytes
```
f=
_=>~~(109876/54+3-21)
console.log(f())
```
If the "countdown" went to 0, it could be done in 19 bytes.
```
f=
_=>109876/54+3-21|0
console.log(f())
```
And, seeing as it's 2017 now, that can also be done in 21 bytes:
```
f=
_=>-~(109876/54+3-21)
console.log(f());
```
]


[Question]
      [
# Binary to decimal converter
As far as I can see, we don't have a simple binary to decimal conversion challenge.
---
Write a program or function that takes a positive binary integer and outputs its decimal value.
You are not allowed to use any builtin base conversion functions. Integer-to-decimal functions (e.g., a function that turns `101010` into `[1, 0, 1, 0, 1, 0]` or `"101010"`) are exempt from this rule and thus allowed.
Rules:
* The code must support binary numbers up to the highest numeric value your language supports (by default)
* You may choose to have leading zeros in the binary representation
* The decimal output may not have leading zeros.
* Input and output formats are optional, but there can't be any separators between digits. `(1,0,1,0,1,0,1,0)` is not a valid input format, but both `10101010` and `(["10101010"])` are.
	+ You must take the input in the "normal" direction. `1110` is `14` not `7`.
Test cases:
```
1
1
10
2
101010
42
1101111111010101100101110111001110001000110100110011100000111
2016120520371234567
```
This challenge is related to a few other challenges, for instance [this](https://codegolf.stackexchange.com/questions/68247/convert-a-number-to-hexadecimal), [this](https://codegolf.stackexchange.com/questions/63564/simplify-binary) and [this](https://codegolf.stackexchange.com/questions/69155/base-conversion-with-strings).

[Answer]
# Clojure, ~~114~~ ~~105~~ ~~63~~ 41 bytes
## V4: 41 bytes
-22 bytes thanks to @cliffroot. Since `digit` is a character, it can be converted to it's code via `int`, then have 48 subtracted from it to get the actual number. The map was also factored out. I don't know why it seemed necessary.
```
#(reduce(fn[a d](+(* a 2)(-(int d)48)))%)
```
## V3: 63 bytes
```
(fn[s](reduce #(+(* %1 2)%2)(map #(Integer/parseInt(str %))s)))
```
-42 bytes (!) by peeking at other answers. My "zipping" was evidently very naïve. Instead of raising 2 to the current place's power, then multiplying it by the current digit and adding the result to the accumulator, it just multiplies the accumulator by 2, adds on the current digit, then adds it to the accumulator. Also converted the reducing function to a macro to shave off a bit.
Thanks to @nimi, and @Adnan!
Ungolfed:
```
(defn to-dec [binary-str]
  (reduce (fn [acc digit]
            (+ (* acc 2) digit))
          (map #(Integer/parseInt (str %)) binary-str)))
```
## V2: 105 bytes
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range)(reverse %)))
```
-9 bytes by reversing the string so I don't need to create an awkward descending range.
## V1: 114 bytes
Well, I'm certainly not winning! In my defense, this is the first program I've ever written that converts between bases, so I had to learn how to do it. It also doesn't help that `Math/pow` returns a double that requires converting from, and `Integer/parseInt` doesn't accept a character, so the digit needs to be wrapped prior to passing.
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range(dec(count %))-1 -1)%))
```
Zips the string with a descending index representing the place number. Reduces over the resulting list.
Ungolfed:
```
(defn to-dec [binary-str]
  (reduce (fn [acc [place digit]]
            (let [parsed-digit (Integer/parseInt (str digit))
                  place-value (long (Math/pow 2 place))]
              (+ acc (* parsed-digit place-value))))
          0
          (map vector (range (dec (count binary-str)) -1 -1) binary-str)))
```
[Answer]
# Perl, ~~21~~ ~~19~~ 16 + 4 = 20 bytes
-4 bytes thanks to @Dada
Run with `-F -p` (including the extra space after the `F`). Pipe values to the function using `echo -n`
```
$\+=$_+$\for@F}{
```
Run as `echo -n "101010" | perl -F -pE '$\+=$_+$\for@F}{'`
I feel this is sufficiently different from @Dada's answer that it merits its own entry.
Explanation:
```
-F                              #Splits the input character by character into the @F array
-p                              #Wraps the entire program in while(<>){ ... print} turning it into
while(<>){$\+=$_+$\for@F}{print}
                   for@F        #Loops through the @F array in order ($_ as alias), and...
          $\+=$_+$\             #...doubles $\, and then adds $_ to it (0 or 1)...
while(<>){              }       #...as long as there is input.
                         {print}#Prints the contents of $_ (empty outside of its scope), followed by the output record separator $\
```
This uses my personal algorithm of choice for binary-to-decimal conversion. Given a binary number, start your accumulator at 0, and go through its bits one by one. Double the accumulator each bit, then add the bit itself to your accumulator, and you end up with the decimal value. It works because each bit ends up being doubled the appropriate number of times for its position based on how many more bits are left in the original binary number.
[Answer]
# Haskell, 31 bytes
```
f=foldl(\a b->2*a+(read$b:[]))0
```
Takes input in string format (e.g. `"1111"`). Produces output in integer format (e.g. `15`).
`:[]` Converts from an element to an array -- in this chase from `Char` to `[Char]` (`String`).
`read` Converts from string to whatever context it's in (in this case the context is addition, so converts to `Num`)
so `(read$b:[])` converts `b` from `Char` to `Num`.
`a` is the accumulator, so multiply that by two and add the `Num` version of `b`.
If input in the format `[1,1,1,1]` was allowed, the 18 byte
```
f=foldl((+).(2*))0
```
would work, but since it's not, it doesn't.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
(++⊢)/⌽⍎¨⍞
```
`⍞` get string input
`⍎¨` convert each character to number
`⌽` reverse
`(`...`)/` insert the following function between the numbers
 `++⊢` the sum of the arguments plus the right argument
---
ngn shaved 2 bytes.
[Answer]
# [7](https://esolangs.org/wiki/7), 25 bytes (65 characters)
```
07717134200446170134271600446170001755630036117700136161177546635
```
[Try it online!](https://tio.run/##NcjBDcBADALBlpbYhv4rc@4iRXyGzS6JouoHuq1wHfm/oMy4oCzlBB18nLZrdsXdCw)
## Explanation
```
0**77**                             Initialize counter to 0 (an empty section)
   17134200..77546635           Push the main loop onto the frame
```
Once the original code has finished executing, the frame is
```
||**6**||**7**13420044**7**013427160044**7**000175563003**77**7001361**77**7546**35**
```
The last section of this is the main loop, which will run repeatedly until it gets deleted. All of it except the last two commands is data and section separators, which push commands onto the frame to leave it as:
```
||**6**|| (main loop) |**73426644**|**67342**1**6644**|**6667**55**3663**||0013**7**||54
```
**`3`** outputs the last section (`54`) and discards the last two bars. On the first iteration, `5` is interpreted as a switch to output format 5 ("US-TTY"), which converts each pair of commands to a character. The `4` following it does not form a group, so it is ignored. On future iterations, we are already in output format 5, so `54` is interpreted as a group meaning "input character". To do this, the character from STDIN is converted into its character code (or, on EOF, `-1`), and 1 is added. Then, the last section (which is now the `00137`) is repeated that many times. In summary:
* If the character is `0`, `00137` is repeated 49 times.
* If the character is `1`, `00137` is repeated 50 times.
* If there are no more characters, `00137` is repeated 0 times (i.e. deleted).
* If this was the first iteration, `00137` is left alone (i.e. repeated 1 time).
**`5`** removes the last section (`00137` repeated some number of times) from the frame and executes it, resulting in this many sections containing **`6673`**.
The main loop has now finished executing, so the last section (which is **`6673`** unless we reached EOF) runs. **`66`** concatenates the last three sections into one (and has some other effects that don't affect the number of sections), which **`73`** deletes. Thus, the last three sections are deleted, and this repeats until the last section is no longer **`6673`**.
* If we reached EOF, nothing happens.
* If this is the first iteration or the character was `0`, after removing the last three sections 0 or 16 times, there is just one copy left on the frame. This copy deletes itself and the two sections before it, leaving everything up to the main loop and the section after it.
* If the character was `1`, after removing the last three sections 17 times, all 50 copies and the third section after the main loop (the EOF handler) have been deleted.
Now, the last section left on the frame runs. This could, depending on the inputted character, be any of the three sections after the main loop.
If this is the first iteration or the character was `0`, the section just after the main loop, **`73426644`**, runs.
**`73`** deletes this section, and **`4`** swaps the main loop with the counter behind it. This counter keeps track of the number we want to output, stored as the number of `7`s and `1`s minus the number of `6`s and `0`s. This metric has the property that it is not changed by pacification (which changes some `6`s into `0`s, some `7`s into `1`s, and sometimes inserts `7...6` around code). **`2`** duplicates the counter and **`6`** concatenates the two copies (after pacifying the second, which, as we saw, does not change the value it represents), so the value is doubled. If this was the first iteration, the counter was previously empty, and doubling it still results in an empty section. Then, **`6`** gets rid of the empty section inserted by **`4`** (and pacifies the counter again, leaving the value unchanged), and **`44`** swaps the counter back to its original position. This leaves two empty sections on the end of the frame, which are removed automatically, and the main loop runs again.
If the character was `1`, the second section after the main loop (`**67342**1**6644**`) runs. This is just like the section before it (explained in the last paragraph), except for two extra commands: a **`6`** at the start, which joins the section with the previous one before **`73`** deletes it, and a `1` in the middle, which adds a `7` to the counter (increasing its value by 1) after it gets doubled.
If we reached EOF, the third section after the main loop (`**6667**55**3663**`) runs. **`666`** joins the last four sections (everything after the counter) into one section, to be deleted by **`3`**. `**7**55**3**` exits output format 5 by outputting `55` and deletes the section before it, leaving only `||**6**| (counter)` on the frame. **`66`** pacifies the two sections and combines them, turning the **`6`** back into a `0` (and not changing the value of the counter). Finally, the last **`3`** outputs everything.
The `0` at the start enters output format 0 ("Numerical output"), and the rest of the section (i.e. the counter) is converted to a number by taking the number of `7`s and `1`s minus the number of `6`s and `0`s. This value, which is the input converted from binary, is output in decimal and the program terminates.
[Answer]
# Excel, ~~74 70~~ 55
Trailing parens already discounted. Tested in Excel Online.
## Formulae:
* `A1`: Input
* `B1`: `=LEN(A1)` (7)
### Main Code (48):
A pretty simple "add all the powers of 2" formula:
```
=SUM(MID(A1,1+B1-SEQUENCE(B1),1)/2*2^SEQUENCE(B1))
```
Verify with:
```
=DECIMAL(A1,2)
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 37 bytes
*-11 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)*
```
sum(utf8ToInt(scan(,""))%%2*2^(31:0))
```
Takes input as a string, left-padded with 0s to 32 bits. [Try it online!](https://tio.run/##K/r/v7g0V6O0JM0iJN8zr0SjODkxT0NHSUlTU1XVSMsoTsPY0MpAU/O/kgFOYAiGSv8B "R – Try It Online")
I copied some good ideas from [djhurio](https://codegolf.stackexchange.com/users/13849)'s [much earlier R answer](https://codegolf.stackexchange.com/a/102320/16766), so go give that an upvote too. As with the first solution there, this solution won't work for the last test case because it's too large to fit into R's default size of integer.
### Explanation
To get a vector of the bits as integers 0 and 1, we use `uft8ToInt` to convert to a vector of character codes. This gives us a list of 48s and 49s, which we take mod 2 to get 0s and 1s.
Then, to get the appropriate powers of 2 in descending order, we construct a range from 31 down to 0. Then we convert each of those numbers to the corresponding power of two (`2^`).
Finally, we multiply the two vectors together and return their `sum`.
[Answer]
# x86-16 machine code, 10 bytes
**Binary:**
```
00000000: 31d2 acd0 e811 d2e2 f9c3                 1.........
```
**Listing:**
```
31 D2       XOR  DX, DX         ; clear output value
        CHRLOOP:
AC          LODSB               ; load next char into AL
D0 E8       SHR  AL, 1          ; CF = LSb of ASCII char
11 D2       ADC  DX, DX         ; shift CF left into result
E2 F9       LOOP CHRLOOP        ; loop until end of string
C3          RET                 ; return to caller
```
Callable function, input string in `[SI]` length in `CX`. Result in `DX`.
**Example test program I/O:**
[![enter image description here](https://i.stack.imgur.com/4rM2x.png)](https://i.stack.imgur.com/4rM2x.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes
```
(+/2 1*,)/
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LQ1jdSMNTS0dTn4tLnMuQyNABBLkMgCQFgPpACkxAMIQzAGCRrgBAD01wxXFyeVnrq6sbxGjUxlka2WlbqmvEGVgmJRellCoZcaeqeXABdSRgX)
[Answer]
## C, 48 bytes
```
i;f(char *s){for(i=0;*++s;i+=i+*s-48);return i;}
```
Heavily inspired by @edc45 's answer but I made some significant changes. I made 'i' a global variable to save having to typecast. I also used a for loop to save a few bytes. It does now require a single leading 0 in the binary representation.
**More readable version**
```
f(char *s){
  int i = 0; // Total decimal counter
  for(;;*++s;i+=i+*s-48); // Shift left and add 0 or 1 depending on charecter
  return i;
}
```
[Answer]
# k, 8 bytes
Same method as the Haskell answer above.
```
{y+2*x}/
```
Example:
```
{y+2*x}/1101111111010101100101110111001110001000110100110011100000111b
2016120520371234567
```
[Answer]
# JavaScript (ES7), ~~56~~ 47 bytes
Reverses a binary string, then adds each digit's value to the sum.
```
n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
```
**Demo**
```
f=n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
document.write( f('101010') ) // 42
```
[Answer]
# Java 7, 87 bytes
```
long c(String b){int a=b.length()-1;return a<0?0:b.charAt(a)-48+2*c(b.substring(0,a));}
```
For some reason I always go straight to recursion. Looks like an [iterative solution](https://codegolf.stackexchange.com/a/102233/51785) works a bit nicer in this case...
[Answer]
# JavaScript (ES6), 38
Simple is better
```
s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
```
**Test**
```
f=s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
console.log("Test 0 to 99999")
for(e=n=0;n<100000;n++)
{
  b=n.toString(2)
  r=f(b)
  if(r!=n)console.log(++e,n,b,r)
}
console.log(e+" errors")

```
[Answer]
# Turing Machine Code, 272 bytes
(Using, as usual, the morphett.info rule table syntax)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 1 l 1
1 1 0 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 0 l 3
4 * * r 4
4 _ _ r A
```
AKA "Yet another trivial modification of my earlier base converter programs."
[Try it online](http://morphett.info/turing/turing.html?a283209e440e64106cd35d1bc3f181e1), or you can also use test it using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
[Answer]
## JavaScript, ~~18~~ 83 bytes
~~`f=n=>parseInt(n,2)`~~
`f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)`
**Demo**
```
f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)
document.write(f('1011')) // 11
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~8~~, 7 bytes
```
"@oovsE
```
[Try it online!](http://matl.tryitonline.net/#code=IkBvb3ZzRQ&input=JzEwMTAxJw)
One byte saved thanks to @LuisMendo!
[Alternate approach: (9 bytes)](http://matl.tryitonline.net/#code=b290bjpQVypz&input=JzEwMTAxJw)
```
ootn:PW*s
```
[Answer]
# Befunge, ~~20~~ 18 bytes
Input must be terminated with EOF rather than EOL (this lets us save a couple of bytes)
```
>+~:0`v
^*2\%2_$.@
```
[Try it online!](http://befunge.tryitonline.net/#code=Pit-OjBgdgpeKjJcJTJfJC5A&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ)
**Explanation**
```
>             The stack is initially empty, the equivalent of all zeros.
 +            So the first pass add just leaves zero as the current total.
  ~           Read a character from stdin to the top of the stack.
   :0`        Test if greater than 0 (i.e. not EOF)
      _       If true (i.e > 0) go left.
    %2        Modulo 2 is a shortcut for converting the character to a numeric value.
   \          Swap to bring the current total to the top of the stack.
 *2           Multiply the total by 2.
^             Return to the beginning of the loop,
 +            This time around add the new digit to the total.
                ...on EOF we go right...
       $      Drop the EOF character from the stack.
        .     Output the calculated total.
         @    Exit.
```
[Answer]
# Ruby, 37 bytes
```
ruby -e 'o=0;gets.each_byte{|i|o+=o+i%2};p o/2'
         1234567890123456789012345678901234567
```
This depends on the terminating `\n` (ASCII decimal 10) being zero modulo 2 (and on ASCII 0 and 1 being 0 and 1 mod two, respectively, which thankfully they are).
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 40 bytes
```
아빟뱐썩러숙
뎌반뗘희멍파퍄
```
Accepts a string composed of 1s and 0s.
**To try online**
Since the online Aheui interpreter does not allow arbitrary-length strings as inputs, this alternative code must be used (identical code with slight modifications):
Add the character `벟` at the end of the first line (after `우`) length(n)-times.
```
어우
우어
뱐썩러숙
번댜펴퍼망희땨
```
If the input is `10110`, the first line would be `어우벟벟벟벟벟`.
When prompted for an input, do NOT type quotation marks. (i.e. type `10110`, not `"10110"`)
[Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
[Answer]
# ClojureScript, 36 bytes
```
(fn[x](reduce #(+(* 2 %)(int %2))x))
```
or
```
#(reduce(fn[a n](+(* 2 a)(int n)))%)
```
The straightforward reduction. Takes a string as input.
[Answer]
# Minkolang v0.15, ~~23~~ 19 bytes
```
n6ZrI[2%2i;*1R]$+N.
```
[Try it online!](http://play.starmaninnovations.com/minkolang/?code=n6ZrI%5B2%252i%3B*1R%5D%24%2BN%2E&input=1101)
### Explanation
```
n                             gets input in the form of a number
 6Z                           converts to string (so that it is split into an array)
   r                          reverses it
    I                         gets the stack length
     [        ]               for loop with the stack's length as the number of iterations
      2%                       gets the modulo of the ascii value
                               1 =(string conversion)> 49 =(after modulo)> 1
                               0 =(string conversion)> 48 =(after modulo)> 0
        2i;                    raises 2 to the power of the loop counter
           *                   multiplies it by the modulo
            1R                 rotates stack 1 time
              $+              sums everything
                N.            outputs as number and exit
```
[Answer]
# Common Lisp, ~~99~~ ~~88~~ 72 bytes
Takes a string as input
```
(defun f(s)(reduce(lambda(a d)(+ d(* a 2)))(map'list #'digit-char-p s)))
```
Ungolfed:
```
(defun bin-to-dec (bin-str)
  (reduce (lambda (acc digit) (+ digit (* acc 2)))
          (map 'list #'digit-char-p bin-str)))
```
[Answer]
# ><> (Fish) ~~36~~ 28 bytes
```
/i:1+?!v$2*$2%+!| !
/0| ;n~<
```
Edit 1: Forgot to put the output in the original. Added output and used MOD 2 instead of minus 48 to convert ascii to decimal to save the extra bytes lost. (no change in bytes)
Edit 2: Changed the algorithm completely. Each loop now does this; times current value by 2, then add the mod of the input. (saving of 8 bytes)
[Online version](https://fishlanguage.com/playground/BPT5uHb6PgvsRyvrP)
[Try it Online!](http://fish.tryitonline.net/#code=L2k6MSs_IXYkMiokMiUrIXwgIQovMHwgO25-PA&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) - This works with bigger numbers than the above link.
[Answer]
# **C, 44 bytes**
```
d(s,v)char*s;{return*s?d(s,v+=v+*s++-48):v;}
```
Use as follows :
```
int main(){
  printf("%i\n", d("101010",0));
}
```
Remove two bytes and an unused parameter thanks to Steadybox
[Answer]
# **MATLAB, 49 bytes**
```
@(a)dot(int2str(a)-'0',2.^(floor(log10(a)):-1:0))
```
Anonymous function that splits the input into an array with `int2str(a)-'0'`, then does a dot product with powers of 2. Has rounding error for the last test case, will update the solution when I figure out a fix.
[Answer]
# Forth (gforth 0.7.3), 47 bytes
```
: x 2 base ! bl parse s>number drop decimal . ;
```
`: x` - define new word with name 'x'
`2 base !` - set base to binary
`bl parse` - read line until a space (bl) or EOL
`s>number` - try to convert the string to number
`drop` - we only want the converted number and not the success flag
`decimal` - set base to decimal
`.` - print value on top of stack
`;` - end of definition
Test cases:
```
x 1 1  ok
x 10 2  ok
x 101010 42  ok
x 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567  ok
```
[Answer]
# C, ~~41~~ 37 bytes
```
i;b(char*s){i+=i+*s++%2;i=*s?b(s):i;}
```
[Wandbox](http://melpon.org/wandbox/permlink/HSeSFhE9lswSnFlj)
[Answer]
# SmileBASIC, ~~47~~ 44 bytes
```
INPUT B$WHILE""<B$N=N*2+VAL(SHIFT(B$))WEND?N
```
Another program of the same size:
```
INPUT B$WHILE""<B$N=N*2OR"0"<SHIFT(B$)WEND?N
```
[Answer]
# APL(NARS), 26 chars, 52 bytes
```
{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
```
test:
```
  f←{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
  ⎕fmt f"0"
0
~
  f"1"
1
  ⎕fmt f"101010"
42
~~
  f"10"
2
  (≢,f)"11011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
152 4995366924470859583704000893073232977339613183
```
152 bits... It should be limited from memory for store string and numbers.
]


[Question]
      [
## 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](https://oeis.org/A004152) thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in characters wins!

[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
!SO
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IVNP&input=MTA)
```
!   Factorial.
 S  Push characters separately.
  O Sum.
```
[Answer]
## [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes
```
!DS
```
[Try it online!](http://jelly.tryitonline.net/#code=IURT&input=&args=MTA)
Does what you expect:
```
!    Factorial.
 D   Decimal digits.
  S  Sum.
```
[Answer]
## Mathematica, 21 bytes
```
Tr@IntegerDigits[#!]&
```
[Answer]
# 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](https://codegolf.stackexchange.com/a/100844/53667).
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);
}
```
[Answer]
## 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
[Answer]
# Pyth, ~~7~~ 6 bytes
*Thanks to @Kade for saving me a byte*
`sj.!QT`
[Try it online!](https://pyth.herokuapp.com/?code=sj.%21Q10&input=10&debug=0)
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
```
[Answer]
## Haskell, ~~41~~ 40 bytes
```
f x=sum$read.pure<$>(show$product[1..x])
```
Usage example: `f 985` -> `10053`.
Make a list from `1`to `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!
[Answer]
# Python, 54 bytes
```
f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))
```
**[repl.it](https://repl.it/E6Vu)**
[Answer]
## 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()))),""))))
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 8 bytes
```
$+$*++,a
```
[Try it online!](http://pip.tryitonline.net/#code=JCskKisrLGE&input=&args=MTA)
**Explanation**
```
      ,a    # range
    ++      # increment
  $*        # fold multiplication
$+          # fold sum
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 8 bytes
```
rim!Ab:+
```
[Try it online!](http://cjam.tryitonline.net/#code=cmltIUFiOis&input=MTA)
### Explanation
```
r   e# Read input.
i   e# Convert to integer.
m!  e# Take factorial.
Ab  e# Get decimal digits.
:+  e# Sum.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-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!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmv8ahvqlsQkAgI0HzUNsHQyMJcwdjkfxqQra2v8ai379CKRx0zHvVOBZKKj7oWaf4HqgVKpikYGnDBmZZwprHBfwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes
```
$!@e+
```
[Try it online!](http://brachylog.tryitonline.net/#code=JCFAZSs&input=OTg1&args=Wg)
### 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
```
[Answer]
# 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;
```
[Answer]
# 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.
[Answer]
# [Pushy](https://github.com/FTcode/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
```
[Answer]
# 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 :)
[Answer]
## 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
```
[Answer]
## 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;}
```
[Answer]
# [Perl 6](https://perl6.org), 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
}
```
[Answer]
# 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!](https://ethproductions.github.io/cubix/?code=dSouJHMuISguMDFJXjxXJU5XITs8LDs7cStwQE9wdXM=&input=MTA=&speed=2000)
# 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.
[Answer]
## 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));
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes
```
ḟẹ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO@Q937dT@/9/SwvR/FAA "Brachylog – Try It Online")
Same "algorithm" as the [v1 answer](https://codegolf.stackexchange.com/a/100832/8774) by @Fatalize, just with better encoding.
[Answer]
# Python, 57 bytes
```
import math
lambda n:sum(map(int,str(math.factorial(n))))
```
[**Try it online**](https://repl.it/E6TZ)
[Answer]
## 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
```
[Answer]
## 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.
[Answer]
# [Befunge 93](http://esolangs.org/wiki/Befunge), ~~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!](http://befunge-98.tryitonline.net/#code=JiM6PF92IzotMQo6IFwqJDw6X14jCmc6OnY-OTErJSswMApfdiM8XnAwMDwvKzE5CkA-JCQu&input=MTA)
```
&#:<_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.
```
[Answer]
# 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.
[Answer]
# [AHK](https://autohotkey.com/), 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.
[Answer]
# 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
```
]