title: Print n weird numbers

text:
# Question
Title: Print n weird numbers
A weird number is a number that the sum of proper divisors is greater than the number itself and no subset of proper divisors sum to that number.

Examples:

> 70 is a weird number because its proper divisors (1, 2, 5, 7, 10, 14, and 35) sum to 74, which is greater than 70, and no combination of these numbers sum to 70.
>
> 18 is not a weird number because its proper divisors (1, 2, 3, 4, 6, 9) sum to 25, which is greater than 18, but 3, 6, and 9 sum to 18.

Your task is to write the shortest program that inputs through std-in any number *n* and calculates and prints to a file or std-out the first *n* weird numbers with newline separation. No hard coding of the answers is allowed (sorry for not specifying this in the beginning).

For more examples, see this page: http://mathworld.wolfram.com/WeirdNumber.html

# Answer
> 2 votes
# Mathematica ~~99~~ ~~94~~ 87

Spaces not needed. Slow!:

```
j = i = 0;
While[j<#, i++; If[Union@Sign[Tr /@ Subsets@Most@Divisors@i-i]=={-1, 1}, j++; Print@i]]&

```

At the expense of a few chars this is a faster version that checks only even numbers and skips multiples of `6` that are never weird:

```
j = i = 0;
While[j < #,
      i += 2; If[Mod[i, 6] != 0 && Union@Sign[Tr /@ Subsets@Most@Divisors@i - i] == {-1, 1},
                 j++; Print@i]] &@3

```

it's still too slow for any useful purpose. Finds the first two in a few seconds but gets slower and slower as the number of divisors increase.

# Answer
> 4 votes
# Haskell - 129

I'm sure there's lots to golf here, but since the competition seems low for now I'll throw this in.

Don't try running this though, I managed to wait only the two first elements, third will start taking minutes.

```
(%)=filter
w n=take n$e%[1..]
e x=let d=((==0).mod x)%[1..x-1]in sum d>x&&all((/=x).sum)(i d)
i[]=[[]]
i(y:z)=map(y:)(i z)++(i z)

```

# Answer
> 2 votes
## Ruby - 152

```
x=2;gets.to_i.times{x+=1 while((a=(1..x/2).find_all{|y|x%y==0}).reduce(:+)<=x||(1..a.size).any?{|b|a.combination(b).any?{|c|c.reduce(:+)==x}});p x;x+=1}

```

## Ruby With ActiveSupport - 138

```
x=2;gets.to_i.times{x+=1 while((a=(1..x/2).find_all{|y|x%y==0}).sum<=x||(1..a.size).any?{|b|a.combination(b).any?{|c|c.sum==x}});p x;x+=1}

```

Really slow and I'm almost sure there is still room for golfing...

# Answer
> 2 votes
## Python 2.7 (255 bytes)

```
import itertools as t
a=int(raw_input())
n=1
while a>0:
    d=[i for i in range(1,n/2+1) if not n%i]
    if all([n not in map(sum,t.combinations(d,i)) for i in range(len(d))]+[sum(d)>n]):
        print n
        a-=1
    n+=1

```

# Answer
> 1 votes
## PHP, 267 bytes

```
$n=$x=0;while($n<$argv[1]){$x++;for($i=1,$s=0,$d=array();$i<$x;$i++){if($x%$i){continue;}$s+=$i;$d[]=$i;}if($s<$x){continue;}$t=pow(2,$m=count($d));for($i=0;$i<$t;$i++){for($j=0,$s=0;$j<$m;$j++){if(pow(2,$j)&$i){$s+=$d[$j];}}if($s==$x){continue 2;}}$n++;print"$x\n";}

```

And here's the original source code:

```
$n = 0;
$x = 0;

while ($n < $argv[1]) {
    $x++;

    for ($i = 1, $sum = 0, $divisors = array(); $i < $x; $i++) {
        if ($x % $i) {
            continue;
        }

        $sum += $i;
        $divisors[] = $i;
    }

    if ($sum < $x) {
        continue;
    }

    $num = count($divisors);
    $total = pow(2, $num);

    for ($i = 0; $i < $total; $i++) {
        for ($j = 0, $sum = 0; $j < $num; $j++) {
            if (pow(2, $j) & $i) {
                $sum += $divisors[$j];
            }
        }

        if ($sum == $x) {
            continue 2;
        }
    }

    print "$x\n";
}

```

You will note that it takes some time to output the numbers as it is performing a brute-force verification (you should get to 70 pretty fast, though).

# Answer
> 1 votes
## R, 164

```
r=0;x=1;n=scan();while(r<n){i=which(!x%%(2:x-1));if(sum(i)-1&&!any(unlist(lapply(2:sum(i|T),function(o)colSums(combn(i,o))==x)))&sum(i)>x){r=r+1;cat(x,"\n")};x=x+1}

```

Un-golfed version:

```
r = 0
x = 1
n = scan()
while(r < n) {
  i = which(!x %% (2:x - 1))
  if( sum(i) - 1 &&
       !any(unlist(lapply(2:sum(i | T),
                          function(o) colSums(combn(i, o)) == x))) &
       sum(i) > x
     ){ r = r + 1
        cat(x, "\n")
  }
  x = x + 1
}

```

This takes some time due to brute-force.

# Answer
> 1 votes
## Perl, 176 174 bytes

```
$n=<>;$i=9;X:while($n){@d=grep{!($i%$_)}1..$i-1;$l=0;map{$a=$_;$s=0;$s+=$d[$_]for grep{2**$_&$a}0..@d-1;$i++,next X if$s==$i;$l=1 if$s>$i}0..2**@d-1;$n--,print$i,$/if$l;$i++}

```

The number of weird numbers are expected in STDIN and the found numbers are printed to STDOUT.

## Ungolfed version

```
#!/usr/bin/env perl
use strict;
$^W=1;

# read number from STDIN
my $n=<>;
# $i is the loop variable that is tested for weirdness
my $i=9; # better start point is 70, the smallest weird number
# $n is the count of numbers to find
X: while ($n) {
    # find divisors and put them in array @divisors
    my @divisors = grep{ !($i % $_) } 1 .. $i-1; # better: 1 .. int sqrt $i
    # $large remembers, if we have found a divisor sum greater than the number
    my $large = 0;
    # looping through all subsets. The subset of divisors is encoded as
    # bit mask for the divisors array.
    map {
        my $subset = $_;
        # calculate the sum for the current subset of divisors
        my $sum = 0;
        map { $sum += $divisors[$_] }
            grep { 2**$_ & $subset }
                0 .. @divisors-1;
        # try next number, if the current number is pseudoperfect
        $i++, next X if $sum == $i; # better: $i+=2 to skip even numbers
        $large = 1 if $sum > $i;
    } 0 .. 2**@divisors - 1;
    # print weird number, if we have found one
    $n--, print "$i\n" if $large;
    $i++; # better: $i+=2 to skip even numbers
}
__END__

```

## Limitations

* Slow, brute force.
* The count of divisors for a number is limited to the "bitness" of integers in Perl.

# Answer
> 1 votes
# C++ - 458

This is not all my solution as I had to ask on SO for help calculating the sum of the subsets, but everything else is mine:

```
#include<iostream>
#include<vector>
using namespace std;
#define v vector<int>
#define r return
#define c const_iterator
v x(int i){v d;for(int k=1;k<i;k++)if(i%k==0)d.push_back(k);r d;}bool u(v::c i,v::c e,int s){if(s==0)r 0;if(i==e)r 1;r u(i+1,e,s-*i)&u(i+1,e,s);}bool t(v&d,int i){bool b=u(d.begin(),d.end(),i);if(b)cout<<i<<endl;r b;}int main(){v d;int n;cin>>n;for(int i=2,j=0;j<n;i++){d=x(i);int l=0;for(int k=0;k<d.size();k++)l+=d[k];if(l>i)if(t(d,i))j++;}}

```

Long version:

```
#include<iostream>
#include<vector>
using namespace std;

vector<int> divisors(int i) {

    vector<int> divs;
    for(int k = 1; k < i; k++)
        if(i%k==0)
            divs.push_back(k);
    return divs;
}

bool u(vector<int>::const_iterator vi, vector<int>::const_iterator end, int s) {

    if(s == 0) return 0;
    if(vi == end) return 1;
    return u(vi + 1, end, s - *vi) & u(vi + 1, end, s);
}

bool t(vector<int>&d, int i) {

    bool b = u(d.begin(), d.end(), i);
    if(b) cout<< i << endl;
    return b;
}

int main() {

    vector<int> divs;
    int n;
    cin>>n;

    for(int i = 2, j = 0; j < n; i++) {
        divs = divisors(i);

        int sum_divs = 0;
        for(int k = 0; k < divs.size(); k++)
            sum_divs += divs[k];

        if(sum_divs > i)
            if(t(divs, i))
                j++;
    }
}

```

It has currently only calculated the first two (70 and 836). I killed it after that.

# Answer
> 1 votes
## SageMath: ~~143~~ 131 bytes

```
x=1
def w():
 l=x.divisors()
 return 2*x>=sum(l)or max(2*x==sum(i)for i in subsets(l))
while n:
 while w():x+=1
 print x;n-=1;x+=1

```

It's moreorless not even golfed, there's not too much to golf anyways in the code. The biggest thing is that you should do the test `2*x>=sum(l)` first, it would save a lot of computation time. One has to realize that `max` on booleans is `or` Second thing is that `w(x)` is `False` for weird numbers and `True` for non-weird numbers. Ungolfed version:

```
def w(x) :
 Divisors = x.divisors()
 return 2*x >= sum(Divisors) or max ( sum(SubS) == 2*x for SubS in subsets(Divisors) )

x=1

for k in xrange(n) :
 while w(x) : x += 1
 print x
 x += 1

```

# Answer
> 1 votes
# Smalltalk, 143

```
((1to:(Integer readFrom:Stdin))reject:[:n||d|d:=(1to:n//2)select:[:d|(n\\d)=0].d sum<n or:[(PowerSet for:d)contains:[:s|s sum=n]]])map:#printCR

```

input:

```
1000

```

output:

```
70
836

```

# Answer
> 1 votes
# Perl, 173

Let me add another useless solution. This solution is so slow that it can't even output anything past the first weird number. I dare say it is the slowest of all the solution here.

```
$n=<>;$i=2;while($n){$b=qr/^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+/;$_='x'x3x$i;if(/$b/&&($+[0]>$i)&&!/$b\1{2}$/){print"$i\n";$n--}$i++}

```

Demo

The same code written in Java (which I am more comfortable with) can't even recognize the 2nd weird number (836), and I have already fed the number directly to the checking method (instead of looping and checking every number).

The core of this solution lies in the regex:

```
^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+

```

And how the string is set up to be 3 times the number that we are checking.

The length of the string is set up to be 3 times the number that we are checking `i`: the first 2 `i` is for matching summation of factors and the last 1 `i` is reserved for checking whether a number is a factor of `i`.

`(?=(.+)\1{2}$)` is used to capture the number that we are checking.

`((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+` matches the factors of the number. Later iteration will match a smaller factor than an earlier iteration.

* We can see that these 2 parts `(.+)` and `(?=.*(?=\1$)\3+$)` together selects a factor of the number being checked.
* `(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))` makes sure that the factor selected is smaller than the number being checked in the first iteration, and is smaller than previous factor in subsequent iterations.

The regex tries to match as many factors of the number as it can within the limit of 2 `i`. But we don't care about the actual value of sum of divisors, we only care whether the number is abundant.

Then the 2nd regex, which is the first regex with `\1{2}$` added. As a result, the regex makes sure the sum of (some) factors of the number being checked is equal to the number itself:

```
^(?=(.+)\1{2}$)((.+)(?=.*(?(2)(?=\2$)\3.+$|(?=\1$)\3.+$))(?=.*(?=\1$)\3+$))+\1{2}$

```

The constraint added will cause the regex engine to perform a backtracking search on all possible subsets of factors, so it is going to be extremely slow.

# Answer
> 1 votes
# Jelly, 15 bytes

```
ÆḌŒP§e@=ÆḌS<Ɗµ#

```

Try it online!

Takes input via STDIN.

Insanely inefficient, times out for \\$n \> 1\\$ on TIO, as it checks each \\$k = 1, 2, \dots\\$ until it finds \\$n\\$ values that fit, and for each \\$k\\$ it generates \\$2^{\sigma(k)-k}\\$ sublists (where \\$\sigma(k)\\$ is the sum of divisors function)

## How it works

```
ÆḌŒP§e@=ÆḌS<Ɗµ# - Main link, takes no arguments
             µ# - Take an integer from STDIN, n, and run the previous code over each integer, k, from 0 until n truthy values are found:
ÆḌŒP§e@         -   First check for weirdness:
ÆḌ              -     Take the proper divisors of k
  ŒP            -     Find the powerset of the proper divisors
    §           -     Get the sum of each
                -       This gives the sum of each subset of proper divisors
     e@         -     Is k equal to one of the sums?
                -     This gives 0 if no combination of these numbers sum to k and 1 otherwise
        ÆḌS<Ɗ   -   Second check for weirdness:
            Ɗ   -     Group the previous 3 commands together:
        ÆḌS     -       Is the proper divisor sum of k...
           <    -       Less than k?
                -     This gives 0 if the proper divisor sum of k is greater than k and 1 otherwise
      =         -   Are the two checks equal?
                -     There are three possible values that the two checks could output:
                -        0, 1: k cannot be expressed as a sum of a subset of its proper divisors and k is less than or equal to its proper divisor sum, therefore k is not weird
                -        1, 0: k can be expressed as a sum of a subset of its proper divisors and k is greater than its proper divisor sum, therefore k is not weird
                -        0, 0: k cannot be expressed as a sum of a subset of its proper divisors and k is greater than its proper divisor sum, therefore k is weird
                -     1, 1 cannot be a possibility as that would require that k can be expressed as a sum of a subset of its proper divisors and that k is greater than its proper divisor sum, which are contradictory
                -     Therefore, checking whether the two checks result in the same value suffices to check for weirdness

```

# Answer
> 0 votes
# Python 2, 100 bytes

```
n=input()
i=0
while n:
 i+=1;s=1;d=1
 while d<i:s|=s<<d*(i%d<1);d+=1
 s>>=i
 if s>1>s&1:print i;n-=1

```

Attempt This Online!

I use the integer `s` as a bitset, telling me the sums of divisors of `i`. The k-th bit tells me whether k is a sum of the divisors found.

---
Tags: code-golf, math, number-theory
---


title: The vanilla factorial challenge

text:
# Question
Title: The vanilla factorial challenge
## Task

Given a non-negative integer \\$n\\$, evaluate the factorial \\$n!\\$.

The factorial is defined as follows:

$$ n!=\begin{cases}1 & n=0\\n\times(n-1)!&n\>0\end{cases} $$

## Rules

* All default I/O methods are allowed.
* Standard loopholes are forbidden.
* Built-ins are allowed.
* There is no time or memory limit.
* Giving imprecise or incorrect results for large inputs due to the limit of the native number format is fine, as long as the underlying algorithm is correct. Specifically, it is not allowed to abuse the native number type to trivialize the challenge, which is one of the standard loopholes.
* This is . Shortest code in bytes wins, but feel free to participate in various esolangs (especially the ones hindered by the restrictions of the former challenge).

## Test cases

```
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600

```

---

**Note:** We already have the old factorial challenge, but it has some restrictions on the domain, performance, and banning built-ins. As the consensus here was to create a separate challenge without those restrictions so that more esolangs can participate, here it goes.

Also, we discussed whether we should close the old one as a duplicate of this, and we decided to leave it open.

# Answer
> 33 votes
# Shakespeare Programming Language, 106 bytes

```
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck]Ajax:Listen tothy!You is the factorial ofyou!Open heart

```

Try it online!

Uses the built-in `the factorial of`, which isn't described at all in the official docs.

### Commented

```
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck] # header
Ajax:Listen tothy!                                  # read (numeric) input
You is the factorial ofyou!                         # take factorial
Open heart                                          # numeric output

```

# Answer
> 20 votes
# MATL, 2 bytes

```
:p

```

Try it online!

The `:` generates a range from 1 to input inclusive and the `p` reduces it on product

# Answer
> 19 votes
# C (gcc), 21 bytes

Uses the assignment trick, works consistently in GCC without optimizations.

```
O(o){o=o?o*O(~-o):1;}

```

Try it online!

# Answer
> 18 votes
# x86-16 / x87 machine code, 13 bytes

Binary:

```
00000000: d9e8 e308 518b f4de 0c59 e2f8 c3         ....Q....Y...

```

Listing:

```
D9 E8       FLD1                ; start with 1
E3 08       JCXZ DONE           ; if N = 0, return 1
        FACT_LOOP:
51          PUSH CX             ; push current N onto stack
8B F4       MOV  SI, SP         ; SI to top of stack for N
DE 0C       FIMUL WORD PTR[SI]  ; ST = ST * N
59          POP  CX             ; remove N from stack
E2 F8       LOOP FACT_LOOP      ; decrement N, loop until N = 0
        DONE:
C3          RET                 ; return to caller

```

Callable function. Input **\\$n\\$** in `CX`, output **\\${n!}\\$** in `ST(0)`. Works for values of **\\$n\\$** up to `21` (before loss of precision).

*Or recursive...*

## x86-16 / x87 machine code, 15 bytes

```
D9 E8       FLD1                ; start with 1
        FACT_CALL:
E8 0A       JCXZ DONE           ; if N = 0, end recursion
51          PUSH CX             ; push current N onto stack
49          DEC  CX             ; decrement N
E8 F9FF     CALL FACT_CALL      ; recurse N-1
8B F4       MOV  SI, SP         ; SI to top of stack for N
DE 0C       FIMUL WORD PTR[SI]  ; ST = ST * N
59          POP  CX             ; remove N from stack
        DONE:
C3          RET                 ; return from recursive call

```

*Or x64 just for grins...*

## x86\_64 machine code, ~~12~~ 11 bytes

```
  31:   6a 01            push   0x1             # start with 1
  33:   58               pop    rax
  35:   e3 05            jrcxz  3c <done>       # if 0, return 1
0037 <f_loop>:
  37:   48 f7 e1         mul    rcx             # rax = rax * N
  3a:   e2 fb            loop   37 <f_loop>     # loop until N = 0
003c <done>:
  3c:   c3               ret                    # return to caller

```

Try it online!

Input **\\$n\\$** in `rcx`, output **\\${n!}\\$** in `rax` for values of **\\$n\\$** up to `20`.

* -1 bytes thx to @PeterCordes on x86\_64!

# Answer
> 11 votes
## Google Sheets / Excel / Numbers, 8 bytes

```
=FACT(A1

```

All three spreadsheet programs close parentheses automatically.

# Answer
> 11 votes
# brainfuck, 56 bytes

```
+>,[[>+>+<<-]>[-<<[->+<<+>]<[->+<]>>>]<<[-]>[->+<]>>-]<.

```

Try it online!

Takes input and outputs as byte values. Since this interpreter has 8 bit size cells, it can't really do anything larger than `5!`. You can use this interpreter to try larger values.

# Answer
> 10 votes
# Retina, 29 bytes

```
.+
*
.
$.<'$*
~`.+
.+¶$$.($&_

```

Try it online! Explanation:

```
.+
*

```

Convert `n` to unary.

```
.
$.<'$*

```

Count down from `n` in decimal, with trailing `*`s.

```
~`.+
.+¶$$.($&_

```

Wrap the result in a Retina replacement stage and evaluate it.

Example: For `n=10`, the resulting stage is as follows:

```
.+
$.(10*9*8*7*6*5*4*3*2*1*_

```

This calculates the length of the string obtained by repeating the `_` by each of the numbers from `1` to `10`.

Explanation for `n=0`:

```
.+
*

```

Delete the input.

```
.
$.<'$*

```

Do nothing.

```
~`.+
.+¶$$.($&_

```

Do nothing, and evaluate the resulting empty stage on the empty string.

The empty stage returns `1` more than the character count. As the string is empty, this is just `1`. Conveniently, this is the result we wanted all along.

It is of course possible to calculate the factorial properly even for `n=0`, but my best attempt took 30 bytes.

# Answer
> 10 votes
# Wolfram Language (Mathematica), 11 bytes

```
Gamma[#+1]&

```

Try it online!

# Wolfram Language (Mathematica), 15 bytes

```
1~Pochhammer~#&

```

Try it online!

# Wolfram Language (Mathematica), 19 bytes

```
If[#>0,#0[#-1]#,1]&

```

Try it online!

# Wolfram Language (Mathematica), 24 bytes

The determinant of the n\*n matrix of reciprocals of beta functions is n!

```
Det[1/Beta~Array~{#,#}]&

```

Try it online!

# Wolfram Language (Mathematica), 26 bytes

```
GroupOrder@*SymmetricGroup

```

Try it online!

# Answer
> 10 votes
# ///, 80 bytes

```
/!1/1!//!/S'SS'.'//1/S.B'S.B|B'SS.B|S|.SS'B|S'SS|B.SxBxSSxBxS|B..S//B/\\//S/\//!

```

Takes input in unary as `1`s appended to the program. Produces output in unary as `.`s.

Try it online!

The program sends the `!` to the end of the input, then makes several more substitutions. After completing the substitutions that exist in the initial program, each `1` from the input has been replaced with the following "1 code" (line breaks added for clarity):

```
/.\"/.\|\"/
/.\|/|./
/"\|/"/
/|\./x\x/
/x\x/|\../

```

and after that, `/'//'.'`.

Each copy of the "1 code" multiplies the number of full stops between the single quotes by 1, then increases the multiplier of the subsequent copies by 1. Many backslashes have been used to ensure that the rest of the code is not modified by earlier copies' execution.

The multiplication is done by adding a `|` at the end, then moving it left, replacing each `.` it passes with `.`, then removing it. To increase the multiplier, `|.` is changed to `|..`, with the intermediate step of `xx`.

Finally, the last substitution removes the single quotes, and the result is printed.

# Answer
> 9 votes
# Java, ~~37~~ 36 bytes

```
int f(int n){return n<2?1:n*f(n-1);}

```

I simply wanted to try to participate although Java is not the best language to have as little bytes as possible.

This is simply the definition coined to Java, with a recursive call.

edit: one byte less, thx @Jo King

# Answer
> 8 votes
# MAWP, 19 bytes

```
@[!1A]%_1A[%W_1A]~:

```

Try it!

# Answer
> 8 votes
# Rattle, ~~23~~ 20 bytes

```
|s>s[0+q][g-s<*~s>]~

```

Try it online!

This is the answer that I could not post on the other challenge! (see this)

Note that I do not have an online interpreter for Rattle yet so the interpreter is mashed together into the header on TIO (which is why TIO thinks it's Python 3 code but what's in the `code` section is only Rattle code - ignore the header and footer).

This actually works for up to `170!` (but will a loss of precision, of course). In the next Rattle update this will actually become a builtin - making the possible solution just two bytes - but for its current version this is likely the shortest and most interesting factorial program.

# Explanation

```
|           takes user's input
s>s         saves the input to memory slots 0 and 1
[0+q]       if the top of the stack is equal to zero: increments, and quits (implicitly prints the top of the stack)
[    ]~     loop n times, where n is the value in storage at the pointer
 g-s         gets the value at the pointer, decrements, and saves
 <           moves pointer left
 *~          pushes product of old top of stack and value at pointer to new top of stack
 s           saves to memory slot at pointer
 >           moves pointer right
             (implicitly outputs the value at the top of the stack after the program executes)

```

In essence, this program saves the given value (from input) to two memory slots. Then, it decrements one memory slot and multiplies the other by the decremented value, until the value decrements to 1, then it outputs the final value.

# Answer
> 8 votes
# TI-BASIC (TI-83), 2 bytes

```
Ans!

```

Takes input via `Ans`. The character count differs from the byte count because TI-BASIC is tokenised; `Ans` and `!` are both 1-byte tokens.

### Sample output

Uses this emulator.

# Answer
> 8 votes
# Miniflak, ~~90~~ 80 bytes

*-10 bytes thanks to @Nitrodon!*

```
{(({})[()])}{}((())){({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}

```

Try it online!

We already have another Brain-Flak answer here, but it uses both stacks and so doesn't work in Miniflak (a restricted subset of Brain-Flak where `<`, `>` and `[]` are disallowed). To avoid the second stack, this program uses a different multiplication algorithm.

### Explanation

```
{(({})[()])}
{          }    # While the top of the stack is nonzero:
   {}           # Pop the stack
  (  )          # Push a copy on the stack
      [()]      # Subtract 1
 (        )     # Push the result

```

This part counts down from the input value to 0, leaving a copy of each number in order.

```
{}((()))
{}              # Pop the zero on the top
  ((()))        # Push 1 twice

```

These extra ones are there so that when the input is 0 or 1, we multiply them together to get 1 instead of accidentally multiplying something by 0.

```
{({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}
{                                                        }    # While the top of the stack is nonzero:
 ({(()[{}]({}))([{}]({}))}({}{})[{}])                         # Multiply the top two values
                                     (({}({}))[({}[{}])])     # Swap the top two values
                                                          {}  # Remove the zero on top

```

This loop is the core of the program: at each step, it multiplies the top two numbers together and then brings the number below them to the top. When we run out of numbers, a zero gets swapped to the top, and the loop ends. We then remove that zero, and the result of multiplying all the numbers together (which is the factorial of the input, as the numbers counted down from it to 1) is left.

How does this multiplication algorithm work?
(Suppose the top two numbers on the stack are `a` and `b`.)

```
({(()[{}]({}))([{}]({}))}({}{})[{}])
      {}                               # Pop a
     [  ]                              # Subtract it ...
   ()                                  # ... from 1
         ({})                          # Add b
  (          )                         # Push the result
               [{}]                    # Subtract that ...
                   ({})                # ... from b ...
              (        )               # and push the result
 {                      }              # Repeat until a reaches 0, keeping a running total of the sum of both results
                          {}{}         # Pop a and b, add them together, ...
                         (    )[{}]    # ... and ignore the result
(                                  )   # Push the running total

```

During each run-through, `a` (the top of the stack) is replaced by `b-(b+(1-a))`, which equals `a-1`. This repeats until `a` reaches 0, so the number of iterations is equal to the first input. The running total keeps track of the sum of the two results at each iteration. The first result is `b+(1-a)` and the second is `a-1`, so their sum is always `b`, the second input. This means that keeping track of the running total yields the product of the two inputs. Finally, before pushing the product, we pop `a` and `b` because we don't need them anymore.

The last piece is the swapping algorithm:

```
(({}({}))[({}[{}])])
  {}                  # Pop the top number
    ({})              # Add the second number
 (      )             # Push the result
           {}         # Pop the sum
              {}      # Pop the second number ...
             [  ]     # ... and subtract it from the sum
          (      )    # Push the result (the first number) ...
         [        ]   # ... and subtract that from the previous result (the sum)
(                  )  # Push the final result (the second number)

```

Since the first number is pushed back before the second one, their order is swapped from before.

# Answer
> 7 votes
# JavaScript (Node.js), 17 bytes

```
y=x=>x?x*y(x-1):1

```

Try it online!

# Answer
> 7 votes
# CJam, 4 bytes

```
rim!

```

Try it online

I'm sure there's other 4-bytes solutions, but I quite like how this makes an English word with punctuation, even if exclaiming "rim!" without context seems absurd.

# Answer
> 6 votes
# QBasic, 37 bytes

```
INPUT n
f=1
FOR i=1TO n
f=f*i
NEXT
?f

```

If `n` is zero, the for loop does nothing and 1 is output. Otherwise, the for loop runs over `i` from 1 up to and including the input number, multiplying the result by each `i`.

The values here are single-precision by default, which means that after 10! we start getting output in scientific notation. The values are still accurate for 11! and 12!, though (e.g. 12! gives `4.790016E+08`). At 13! we start to see rounding error (`6.227021E+09` for 6227020800). If we use a double-precision variable `f#` in place of `f` (+4 bytes), we get accurate results up to 21!.

# Answer
> 6 votes
# Rust, 27 bytes

Closure that takes `n` as its input. Thanks to madlaina

```
|n|(1..=n).fold(1,|f,x|f*x)

```

Sample wrapper program to call closure (111 bytes).

```
fn main(){let f=|n|(1..=n).fold(1,|f,x|f*x);print!("{}",f(std::env::args().nth(1).unwrap().parse().unwrap()));}

```

Try it online!

# Rust, 104 bytes

```
fn main(){print!("{}",(1..=std::env::args().skip(1).next().unwrap().parse().unwrap()).fold(1,|f,x|f*x))}

```

Try it online!

Rust sure isn't built for golfing, but 'twas interesting to do so! Takes `n` via program arguments. Conveniently fails at `13!`

I'm certain a fair number of bytes can be shaved from this, possibly if the `unwrap()` calls can be eliminated using `?` and a `Result`.

# Answer
> 6 votes
# Rust, 20 bytes

```
|n|(1..=n).product()

```

Try it online!

# Answer
> 6 votes
# ArnoldC, 409 bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE f
YOU SET US UP 1
HEY CHRISTMAS TREE x
YOU SET US UP 0
GET YOUR ASS TO MARS x
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
STICK AROUND x
GET TO THE CHOPPER f
HERE IS MY INVITATION f
YOU'RE FIRED x
ENOUGH TALK
GET TO THE CHOPPER x
HERE IS MY INVITATION x
GET DOWN 1
ENOUGH TALK
CHILL
TALK TO THE HAND f
YOU HAVE BEEN TERMINATED

```

Try it online!

Iterative approach, it just loops starting from the input number and decreasing it until it reaches 0.

# Answer
> 6 votes
# convey, 16 bytes

```
 }>-1
1@"v
^*",{

```

Try it online!

Loops over the input value until it reaches `0`. There may be a shorter way using the indices command (`/.`), but it seems to take up more logic than I want. Since the interpreter includes a handy-dandy gif maker, you can even see it in action.

# Answer
> 5 votes
# , 1 byte

```
!

```

Try it online!

Works for APL too

# Answer
> 5 votes
# Jelly, 1 byte

```
!

```

Try it online!

# Answer
> 5 votes
# Bash, 13 bytes

```
seq -s* $1|bc

```

Try it online!

# Answer
> 5 votes
# R, 15 bytes

```
gamma(scan()+1)

```

There is also `factorial` which appears to be allowable as a 9-byte solution.

# Answer
> 5 votes
# Pip, 5 bytes

```
$*\,q

```

Try it online!

# Answer
> 5 votes
# Mini-Flak, 56 bytes

```
{(({}[()])({({}({}))[({}[({})()])]}{}{})[({})])}{}({}())

```

Try it online!

When golfing a fold operation in Brain-Flak, it is generally better to keep the stack small and use a "generator" than to push the entire list at once. I'm not exactly why this is true, but it typically works out that way. In this case, it avoids an entire swap operation, since the loop index can stay on top the whole time.

The other main optimization is to make the bottom of the stack equal the running total *minus 1*. This 1 has to be added back later, but this is shorter than pushing a 1 below the input at the beginning.

The multiplication algorithm here is a variant of the swap algorithm. Specifically, there are two equivalent swap algorithms: `(({}({}))[({}[{}])])` calculates B as `(A + B) - A`, while `(([{}]({}))([{}]{}))` calculates B as `(B - A) + A`. To use this in a multiplication loop, we can modify these to not destroy B, and also decrement A by 1. There are three ways to add a single `()` to decrement A:

* `([{}]()({}))([{}]({}))` evaluates to `B`.
* `([{}]({}))([{}()]({}))` evaluates to `B - 1`
* `({}({}))[({}[({})()])]` evaluates to `B + 1`

The latter is what we want, since B is one less than the factor I actually want to represent. By multiplying `A - 1` by `B + 1` and then adding `B`, we obtain `A(B+1) - 1` as desired.

```
# Running counter: A
# Running product: B+1

# Start main loop
{

  (

    # Subtract 1 from A
    ({}[()])

    # Multiply by B+1
    ({({}({}))[({}[({})()])]}

    # Add B to get A(B+1) - 1 and push
    {}{})

  # Cancel out product to push A-1 again
  [({})])

}{}

# Add 1 to get final result
({}())

```

# Answer
> 5 votes
# jq, 30 bytes

```
reduce(range(.)+1)as$i(1;.*$i)

```

Try it online!

My first jq answer.

I spent a while trying to get `while` and `foreach` to do my bidding. Thankfully this existed.

# jq, 38 bytes

```
def f(x):if x>0then x*f(x-1)else 1end;

```

Try it online!

A recursive function. `reduce` is a shorthand for a function like this.

# Answer
> 5 votes
# Quipu, 64 bytes

```
\/1&1&0&2&
3&++[][][]
>>3&**1&/\
1&[]1&++
;;%%>>1&
3&4&1&??
??==

```

Try it online!

I decided to try out Quipu for LYAL event, and it's pretty fun to finagle with. I originally had this answer on the other factorial question, not realizing that it was invalid due to overflow.

Ungolfed:

```
"0  1  2  3  4
---------------"
 \/ 1& 1& 0& 2&
 3& ++ [] [] []
 >> 3& ** 1& /\
 1& [] 1& ++
 ;; %% >> 1&
 3& 4& 1& ??
 ?? ==

```

Thread 0 takes input, then jumps to thread 3 if `N > 0`, otherwise it sets its value to 1 and jumps to thread 3.

Thread 3 then takes the value of thread 0 (`N if N > 0, else 1`) and increments it by 1 (we'll call this `M`), then jumps to thread 1.

Thread 1 increments its value, which acts as the accumulator (`acc`), and if `acc == M`, it jumps to thread 4, otherwise it jumps to thread 2.

Thread 2 takes its value (`X`) and multiplies it by `acc`. If `X != 0`, it jumps back to thread 1, otherwise it sets `X` to 1 and jumps to thread 3.

Once `acc` reaches `M`, execution jumps to thread 4, which prints the value of thread 2.

# Answer
> 5 votes
# Prolog (SWI), 61 bytes

```
0+1.
N+F:-nth1(N,_,_),Y is N-1,Y+G,(F is G*N->1>0;F<G,!,0>1).

```

Try it online!

Steffan's answer is much shorter at 28 bytes, but this predicate was created to be as general as possible. It can be used to:

* Validate that N! = F (for example, `5+120` will succeed, `6+120` will fail)
* Calculate `N!` (`5+F` will bind `F` to `120`)
* Calculate `N` from `N!` (`N+120` will bind `N` to `5`)
    + `N+1` has both `0` and `1` as possible values
    + A non-factorial will fail the predicate
* Generate all `N`, `N!` pairs

The last section feels like it can be golfed, especially as it has both `0>1` as always true and `0<1` as always false, but I've been staring at it for a while and can't figure out anything better. Pity that `\+!` doesn't work.

# Answer
> 5 votes
# TypeScript Type System, ~~98~~ 99 bytes

```
type X<A,B=A>=B extends`1${infer R}`?R extends""?A:B extends A?X<B,X<R>>:`${A&string}${X<R,A>}`:"1"

```

Try it at the TypeScript playground

+1 byte to make `X<0>` work properly

I/O is unary strings.

Go check out emanresu A's really clean golf of this! It uses pretty much the same formula but the execution is really great.

It took me a little over an hour to come up with and golf. It's pretty hard to explain but the gist of it is that `X<A>` does the factorial, and `X<A,B>` does multiplication. It figures out which is being used by making `B` default to `A` if not specified, and checking if `B extends A`. I was able to get it so short by combining the types for factorial and multiplication, since they shared a lot of boilerplate.

I also wrote a version that uses decimal I/O for ~~184~~ 175 bytes:

```
//@ts-ignore
type X<A,B=[]>=A extends 1[]?B extends[1,...infer R]?R extends[]?A:B extends A?X<A,X<R,R>>:[...A,...X<R,A>]:[1]:B extends{length:A}?X<B,B>["length"]:X<A,[...B,1]>

```

Try it at the TypeScript playground

@tjjfvi showed me this spectacular 153 byte version with I/O in decimal:

```
//@ts-ignore
type M<A,B,N=[]>=A extends[0,...infer A]?M<A,B,[...N,...B]>:N;type F<N,X=[],A=[0],L="length">=X[L]extends N?A[L]:F<N,[0,...X],M<[0,...X],A>>

```

Try it at the TypeScript playground

# Answer
> 4 votes
# Brain-Flak, 52 bytes

```
<>(())<>{(({}[()]))({<>({})<><({}[()])>}{}<>{})<>}<>

```

Try it online!

Posting my own Brain-Flak solution, which differs from the same size one from the older challenge.

# Answer
> 4 votes
# Befunge-93, ~~20~~ 19 bytes

```
&+#v:!_:
\@#<*_\:.#

```

Try it online!

Reposting more of my answers from the old challenge that didn't fit the requirements. This one didn't get up to `125!`, at least with this interpreter.

## Explanation:

```
&           Get the input
 +          Add it to the current counter (initially 0)
    :!_     Duplicate and check if it is zero
&+     :    If not, duplicate and repeat, but add the -1 from EOF to the input
  #v:!      If it is, not the 0 into a 1, duplicate and go to the second line
            This initialises the stack as n,n-1,n-2...,1,1,1
   <        Start going left
\    _ :    Check if the second element on the stack is zero
    *       If not, then multiply the top two elements
 @#   \ .#  If it is, then print the factorial value and terminate

```

I believe this was actually my first answer on this site, with the below being the 20 byte version of the above.

# Befunge-93, 20 bytes

```
1&0>-#1:__\#0:#*_$.@

```

Try it online!

# Answer
> 4 votes
# Funky 2, ~~22~~ 18 bytes

Saved 4 bytes through ovs's optimization.

```
f=x=>x<1orx*f(x-1)

```

When `x<1`, returns `1` (Due to `x<1` being truthy), Otherwise returns `x*f(x-1)`, recursively getting the factorial/

Try it online!

# Answer
> 4 votes
# Haskell, 17 bytes

```
f n=product[1..n]

```

Try it online!

* Thanks to 79037662 for suggesting it!

18 bytes

```
f 0=1
f x=x*f(x-1)

```

Try it online!

Or 19 bytes using **fold**.

```
f n=foldr(*)1[2..n]

```

Try it online!

# Answer
> 4 votes
# Ly, 9 bytes

```
1fR[s*]pl

```

Try it online!

Ly, for some reason, doesn't have `&*` (product) like it does `&+` (sum). I guess I forgot about it 3 years ago when I made this terrible language.

# Answer
> 4 votes
# Regex  (RME / PCRE2 v10.35+), 12 bytes

```
^((?*x+)x)*$

```

Attempt This Online! \- PCRE2
Try it on replit.com! \- RegexMathEngine, in ECMAScript+`(?*)` mode

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)

```
^           # tail = N = input number
(
    (?*x+)  # Assert tail > 0; multiply the number of possible matches by tail
    x       # tail -= 1
)*          # Iterate the above as many times as possible, minimum zero
$           # Assert tail == 0, so that the loop will have iterated N times

```

This solution uses `(?*`...`)` non-atomic lookahead. It (and any super-exponential function) is likely impossible to implement without some kind of non-atomic lookaround (which would be necessary for compatibility with other regex engines, e.g. Perl).

The problem is, without molecular lookahead, it's necessary to actually advance the cursor (subtract a value from \\$tail\\$) to try different possibilities in a way that scales with \\$n\\$. Without using molecular lookaround or advancing the cursor, the number of possibilities can only be multiplied by a constant, e.g. `()?()?()?` or `(|){3}` to multiply them by \\$2^3\\$, or `(||){9}` to multiply them by \\$3^9\\$.

For example, without molecular lookahead, \\$2^n\\$ can be implemented as `^(x|x)*$` or `^(x+)*`, \\$3^n\\$ as `^(x(||))*$` or `^((x+)*)+`, and \\$17^n\\$ as `^(x((|){4}|))*$` or `^(((((x+)*)+)+)+)+`. (The former method can be used for any \\$k^n\\$, and the latter for \\${(2^k+1)}^n\\$.) Going off the rails a bit, there are also options like `^(((((x*)*)*)*)*)*` for \\$\lceil{{80\over 17}154^n}\rceil+1\\$.

But for a problem like Factorial, advancing the cursor by more than \\$1\\$ character per iteration wouldn't leave room for subsequent iterations to have access to the values of \\$tail\\$ they need.

Note: I accidentally posted this on the wrong Factorial challenge on 2022-07-25. As the amount of time it takes is proportional to the result, it can't even calculate \\$12!\\$ in under a minute, so that is not the correct place for it. I have deleted it from there and reposted it here.

# Answer
> 4 votes
# Prolog (SWI), 28 bytes

```
N+X:-N>0,N-1+Y,X is Y*N;X=1.

```

Try it online!

# Answer
> 3 votes
# tinylisp, 34 bytes

```
(load library
(q((n)(product(1to n

```

Try it online! (Code has +4 bytes for assigning the lambda function to a name.)

### Explanation

Using the library functions `product` and `1to`:

```
(q             Quote the following list, which can then be treated as a lambda function
 ((n)          that takes a single argument n:
  (product      Multiply together (if the list is empty, returns 1)
   (1to n))))   all numbers from 1 up to and including n

```

# Answer
> 3 votes
# Zephyr, 72 bytes

```
input n as Integer
set f to 1
for i from 1to n
set f to f*i
next
print f

```

Try it online!

Same algorithm as my QBasic answer, just in a more-verbose syntax: If `n` is zero, the for loop does nothing and 1 is output. Otherwise, the for loop runs over `i` from 1 up to and including the input number, multiplying the result by each `i`.

# Answer
> 3 votes
# Assembly (MIPS, SPIM), 108 bytes, 6\*10 = 60 assembled bytes

```
main:li $v0,5
syscall
li $a0,1
beqz $v0,e
f:mul $a0,$a0,$v0
sub $v0,$v0,1
ble $v0,0,e
b f
e:li $v0,1
syscall

```

Try it online!

## Explanation

```
main:
    li $v0, 5                  # set syscall code 5
    syscall                    # Read an integer into v0
    li $a0, 1                  # register a0 = 1
    beqz $v0, end              # Handle $v0 = 0 case
    fact:                      # Main procedure:
        mul $a0, $a0, $v0      #     a0 = a0 * v0
        sub $v0, $v0, 1        #     v0 = v0 - 1
        ble $v0, 0, end        #     If v0 <= 0, jump to end
        b fact                 #     Jump back to the start of the procedure
    end:                       # After-process:
        li $v0, 1              #     Set sycall code 1
        syscall                #     Output the number stored in a0

```

# Answer
> 3 votes
# Ruby, ~~23~~ 19 bytes

```
->n{Math.gamma n+1}

```

-4 bytes using gamma function (Dingus).

Try it online!

# Answer
> 3 votes
# Io, 20 bytes

```
method(\,\factorial)

```

Try it online!

# Answer
> 3 votes
# Python 2, 38 bytes

```
i=n=1;exec"n*=i;i+=1;"*input();print n

```

Try it online!

# Answer
> 3 votes
# K (ngn/k), 6 bytes

**Solution:**

```
*/1+!:

```

Try it online!

**Explanation:**

```
*/1+!: / the solution
    !: / range 0..N
  1+   / add 1 (vectorised)
*/     / product

```

**Extra:**

* Also `*/-!-:` for the same byte count.

# Answer
> 3 votes
# Pepe, 57 bytes

3 bytes have been decreased from my Pepe factorial program.

```
rrEEReREEEEErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE

```

Try it online!

# Answer
> 3 votes
# Mornington Crescent, 3788 bytes

**109 lines/ops**

```
Take Northern Line to Embankment
Take Northern Line to Embankment
Take District Line to Parsons Green
Take District Line to Ravenscourt Park
Take District Line to Embankment
Take District Line to Embankment
Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Turnham Green
Take District Line to Victoria
Take District Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take District Line to Notting Hill Gate
Take District Line to Embankment
Take District Line to Embankment
Take District Line to Stamford Brook
Take District Line to Embankment
Take Northern Line to Goodge Street
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Tottenham Court Road
Take Northern Line to Tottenham Court Road
Take Northern Line to Moorgate
Take Northern Line to Moorgate
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Moorgate
Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Euston
Take Victoria Line to Euston
Take Northern Line to Moorgate
Take Northern Line to Moorgate
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Moorgate
Take Northern Line to Moorgate
Take Northern Line to Embankment
Take Northern Line to Embankment
Take Northern Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington
Take District Line to Hammersmith
Take District Line to South Kensington
Take District Line to South Kensington
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to South Kensington
Take District Line to Ravenscourt Park
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith
Take District Line to South Kensington
Take District Line to South Kensington
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to South Kensington
Take Piccadilly Line to South Kensington
Take District Line to Ravenscourt Park
Take District Line to Temple
Take District Line to West Kensington
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington
Take District Line to Hammersmith
Take Piccadilly Line to Eastcote
Take Piccadilly Line to Eastcote
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Eastcote
Take Piccadilly Line to Ealing Common
Take District Line to Ravenscourt Park
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith
Take Piccadilly Line to Eastcote
Take Piccadilly Line to Eastcote
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Eastcote
Take Metropolitan Line to Eastcote
Take Piccadilly Line to Ealing Common
Take District Line to Ealing Common
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington
Take District Line to Stamford Brook
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Stamford Brook
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Ravenscourt Park
Take District Line to Upminster
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith
Take District Line to Embankment
Take District Line to Embankment
Take Northern Line to Angel
Take Northern Line to Embankment
Take Northern Line to Embankment
Take District Line to West Kensington
Take District Line to Embankment
Take Northern Line to Embankment
Take Northern Line to Mornington Crescent

```

**Commented version for some explanations:**

```
Take Northern Line to Embankment
Take Northern Line to Embankment
Take District Line to Parsons Green
Take District Line to Ravenscourt Park         # Save Input in Ravenscourt

Take District Line to Embankment
Take District Line to Embankment

                                               # Create -1

Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Turnham Green
Take District Line to Victoria
Take District Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take District Line to Notting Hill Gate
Take District Line to Embankment
Take District Line to Embankment
Take District Line to Stamford Brook           # Save -1 in Stamford Brook

Take District Line to Embankment

                                               # Create 1

Take Northern Line to Goodge Street
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Tottenham Court Road
Take Northern Line to Tottenham Court Road
Take Northern Line to Moorgate
Take Northern Line to Moorgate
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Moorgate
Take Northern Line to Euston
Take Victoria Line to Seven Sisters
Take Victoria Line to Euston
Take Victoria Line to Euston
Take Northern Line to Moorgate
Take Northern Line to Moorgate
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Moorgate
Take Northern Line to Moorgate
Take Northern Line to Embankment
Take Northern Line to Embankment
Take Northern Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington          # Save 1 in West Kensington

                                               # Save 1 as max value at Bounds Green, so we will later take the largest number between the input and 1 (to handle 0 as an input)

Take District Line to Hammersmith
Take District Line to South Kensington
Take District Line to South Kensington
Take Piccadilly Line to Bounds Green           # Save 1 as max
Take Piccadilly Line to South Kensington

Take District Line to Ravenscourt Park         # Get input
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith
Take District Line to South Kensington
Take District Line to South Kensington
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to South Kensington
Take Piccadilly Line to South Kensington
Take District Line to Ravenscourt Park         # If input is 0 -> now it is 1

Take District Line to Temple                   # Save in jumpstack

                                               # Take Current Result (West Kensington) as first argument to Chalfont & Latimer

Take District Line to West Kensington
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington
Take District Line to Hammersmith
Take Piccadilly Line to Eastcote
Take Piccadilly Line to Eastcote
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Eastcote
Take Piccadilly Line to Ealing Common

                                               # Take Current Value (Ravenscourt Park) as second argument to Chalfont & Latimer

Take District Line to Ravenscourt Park
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith
Take Piccadilly Line to Eastcote
Take Piccadilly Line to Eastcote
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Eastcote
Take Metropolitan Line to Eastcote
Take Piccadilly Line to Ealing Common
Take District Line to Ealing Common

                                               # Save the new result n*(n-1) as the current result at West Kensington

Take District Line to Bank
Take District Line to Hammersmith
Take District Line to West Kensington

                                               # Put -1 (Stamford Brook) as the first argument of the addition in Upminster

Take District Line to Stamford Brook
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Stamford Brook
Take District Line to Hammersmith
Take District Line to Upminster

                                               # Put The current value (Ravenscourt Park) as the second argument of the addition in Upminster -> [decrement], save it in the current value

Take District Line to Ravenscourt Park
Take District Line to Upminster
Take District Line to Bank
Take District Line to Hammersmith
Take District Line to Ravenscourt Park
Take District Line to Hammersmith

Take District Line to Embankment
Take District Line to Embankment

Take Northern Line to Angel                    # Check if we reached 0 as current value, if it equals 0, break the loop and continue here:

Take Northern Line to Embankment
Take Northern Line to Embankment
Take District Line to West Kensington          # Get the final result
Take District Line to Embankment
Take Northern Line to Embankment

Take Northern Line to Mornington Crescent      # Print and exit

```

Try it online!

# Answer
> 3 votes
# Rockstar, ~~70~~ ~~66~~ ~~62~~ ~~61~~ ~~60~~ 55 bytes

```
listen to N
F's1
while N
let F be*N-0
let N be-1

say F

```

Try it here (Code will need to be pasted in)

# Answer
> 3 votes
# GolfScript, 9 bytes

```
1\~,{)*}/

```

Try it online!

```
1\         # Puts 1 under the input, this will be the acumulator
  ~,       # Makes an array with numbers from 0 to (n-1)
    {)*}   # This block goes to the top of the stack without being executed, when executed it increments and multiplies, this avoids multiplying by 0 and also multiplies by n
        /  # Executes the previous block for each number in the array

```

# Answer
> 3 votes
# Whispers v3, 25 bytes

```
> Input
>> 1!
>> Output 2

```

Try it online!

**Squeezed pseudo code**:

```
>> Output ((Input)!)

```

**Explanation**:

As always in Whispers, we run the last line first:

```
>> Output 2

```

This line outputs the result from line 2:

```
>> 1!

```

Use the result from line 1 to calculate the factorial `(line 1)!`

```
> Input

```

Takes the first line of the input.

So we get the squeezed pseudo code:

```
>> Output ((Input)!)

```

# Answer
> 3 votes
# PowerShell Core, ~~37~~ 32 bytes

```
param($a)1..($a+!$a)-join'*'|iex

```

Try it online!

Or recursive:

# PowerShell Core, ~~37~~ 36 bytes

```
filter f{if($_){$_*(--$_|f)}else{1}}

```

Try it online!

All bytes reductions thanks to mazzy :)

# Answer
> 3 votes
# Vyxal, 1 byte

```
¡

```

Try it Online!

Built-in factorial.

---

# No built-in, 2 bytes

```
ɾΠ

```

Explanation:

```
    # Implicit input
ɾ   # Range [1, N]
 Π  # Reduce by multiplication
    # Implicit output

```

Try it Online!

# Answer
> 3 votes
# Python 3, ~~61~~ ~~50~~ 48 bytes

```
a=1
for i in range(int(input())):a*=i+1
print(a)

```

Try it online!

Thanks to Bubbler for shortening the code by 11 bytes. Another thanks to Jo King♦ for shortening the code by 2 bytes.

# Answer
> 3 votes
# Quipu, 41 bytes

```
1&1&1&0&
[]--[][]
**2&0&/\
1&>=>>
>>\/
1&

```

Try it online!

This was written for the Learn you a Lang event (just like Aaron Miller's answer). This turned out surprisingly clean, with only 4 threads and no spaces.

### Explanation

Quipu uses multiple threads (these are each column of two characters). The Scala interpreter I'm using here doesn't need spaces between threads, though the other interpreter on Esoteric IDE *does* need the separation, and actually supports the BigInt needed for factorials above the max integer value.

Anyway, thread zero is where we store the actual factorial value. All threads have the initial value of 0.

```
1&    Push 1
[]    Get the value of thread 1 (where the input number will be stored)
**    Multiply it by the current thread 0 value
1&    Push 1
>>    Jump to thread one if the current value is greater than zero
1&    Otherwise push one to initialise the value (this happens on the first iteration)

```

After jumping, the current thread value is set to the value being checked, in this case, current value multiplied by thread one. When the current value is zero and the input has not yet been retrieved (and is also zero), we don't jump, setting the current value to the last knot (the 1).

Either way we move onto the next thread. Thread one is where we get the input and decrement it over each loop.

```
  1&     Push one
  --     Subtract one from the current value
  2&     Push two
  >=     Jump to thread two if the value is greater than or equal to zero
  \/     Otherwise push the input

```

Similar to thread zero, we initialise this value to the input if it was initially zero. Otherwise, we decrement the value. Next is thread two.

```
    1&     Push 1
    []     Get the value of thread one
    0&     Push zero
    >>     Jump back to thread zero if the value is still greater than zero

```

This loops back over the first two threads until the input has reached zero, multiplying the value of thread zero by each element in the range of 1 to the input. Once we're done, we finally execute thread three and terminate.

```
      0&    Push zero
      []    Get the value of thread zero
      /\    And print

```

# Answer
> 3 votes
# Piet \+ ascii-piet, 34 bytes (2×17=34 codels)

```
tlqrjccskfeurmuuI  ???c?viqdltt ii

```

Try Piet online!

# Answer
> 3 votes
# Knight, 25 bytes

```
;=x+=y 1P;W=x-x 1=y*x yOy

```

Try it online!

Ungolfed:

```
; = x +             x = sum of:
      = y 1           y = 1 (passes through 1) and
      PROMPT          a line from stdin (coerced to number)
; WHILE = x - x 1   while (x = x - 1) is nonzero:
  = y * x y           y = x * y
OUTPUT y            print y

```

In Knight, coercion depends on the type of the first argument. So `1+"5"` is 6 while `"5"+1` is `"51"`.

# Answer
> 3 votes
# Brachylog, 1 byte

Try it online!

Also works with a fixed output and an unknown input, with decent performance.

### No built-in, 3 bytes

```
⟦b×

```

Try it online!

# Answer
> 3 votes
# Raku, 11 bytes

```
{[*] 1..$_}

```

Try it online!

```
{         }  : anonymous code block
 [ ]         : reduction metaoperator
  *          : multiplication
     1..$_   : range from 1..input

```

# Answer
> 3 votes
# K (ngn/k), 6 bytes

```
*/1+!:

```

Try it online!

Explanations:

```
*/1+!:  Main function. Takes implicit input
    !:  Create a range between [0..input-1] (the colon is used to indicate the language to
        create the range instead of modulo)
  1+    + 1 to each of the numbers, leaving us with [1..input]
*/      Fold and multiply

```

# Answer
> 3 votes
# Apple Shortcuts, ~~3~~ 2 actions

Try it for yourself: (Only works on iPads and iPhones, sadly.)

I was messing around with shortcuts, and found that it is a pretty functional programming language. There’s input, basic math, more complex math, lists and some basic list functions, dictionaries, some basic dictionary functions, statistical functions, and the ability to run code in SSH (plus some more advanced functions like hashing and Base64 conversion). The only problem that I can think of is that Shortcuts does not have any form of text-based interface, so instead of bytes, you have to count “actions”, which aren’t exactly “bytes” and are hard to compare with other answers in terms of length.

TLDR I messed with Apple Shortcuts and you should too.

-1 Action! It turns out, actions that need numbers have input built-in, so the “Get number from input” action was unnecessary.

# Answer
> 3 votes
# Piet \+ ascii-piet, 24 bytes (4×10=40 codels)

```
rmttlddqbDlbaltdmu?_ V??

```

Try Piet online!

Similar to below, but realized that I can remove `1 >`. Also, using `B2->B1 = I` (which is a no-op) gave `A2->B2 = D` (which safely removes a 0) and a color sharing for `3`. ~~Luck based golfing?~~

---

# Piet \+ ascii-piet, 27 bytes (5×11=55 codels)

```
rmttldqbdTl?dckmvfnnN TuDuu

```

Try Piet online!

The logic is the same as Parcly Taxel's.

Main loop (`A1 -> A10 -> B9 -> B1 -> A1`):

```
D * 2 1 r       Mostly no-op, just pushes [2 1]
I               Take input [2 1 n]; becomes a no-op afterwards
                Invariant: [2 prod i]
d 1 -           [2 prod i i-1]
3 1 r d 1 > !   [2 i-1 prod i i<=1]
D               [2 i-1 prod i]; turn right at A2 if n <= 1
* 2 1 r         [2 i-1 prod*i]

```

After turn right at A2 (`A2 -> E2`):

```
x O <halt>      Discard i and print prod

```

The main trick here is to move the `DP+` to the cell A2, and rotate the main loop accordingly. This works because most commands are no-op when there are not enough items on the stack yet.

# Answer
> 3 votes
# TypeScript Type System, 82 bytes

```
type X<A,B=A>=A extends`1${infer R}`?B extends`1${infer O}`?`${X<R>}${X<A,O>}`:B:1

```

Try it online!

Quite similar to, but independently derived from noodle man's answer. I also stole their test harness.

This is basically the same as the JavaScript code `f = (a, b = a) => a ? b ? f(a, b - 1) + f(a-1) : 0 : 1`. The idea here is that we have two accumulators, `a` and `b`, where `b` starts at the value of `a`. We repeatedly decrement `b` and add `f(a-1)` to the total, which results in the factorial of `a`.

# Answer
> 3 votes
# Uiua, 5 bytes

```
/×+1⇡

```

Try it!

```
    ⇡  # create range [0..input)
  +1   # amend it to [1..input]
/×     # reduce by multiplication

```

# Answer
> 2 votes
# Keg, `-hr`, 4 bytes

```
Ï_∑*

```

Try it online!

# Answer
> 2 votes
# Pyth, 2 bytes

```
*F

```

Try it online!

Alternate solution:

```
.!

```

# Answer
> 2 votes
# 05AB1E, 1 byte

```
!

```

Try it online!

# Answer
> 2 votes
# Python 3.8, ~~23~~ 21 bytes

Saved 2 bytes thanks to Bubbler!!!

```
import math
math.perm

```

Try it online!

# Answer
> 2 votes
# Charcoal, 8 bytes

```
ＩΠ…·¹∨Ｎ¹

```

Try it online! Link is to verbose version of code. Explanation:

```
      Ｎ     `n` as a number
     ∨      Logical Or
       ¹    Literal `1`
  …·¹       Inclusive range from `1` to `n`
 Π          Take the product
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 2 votes
# Flurry `-nii`, 14 bytes

```
{}{<({})[]>}{}

```

Try it online!

Takes single number from the stack and prints its factorial from the return value.

The online interpreter implements certain arithmetic shortcuts, so it computes and prints `125!` in an instant.

### How it works

Iterate through 1 to `n` using the stack height and multiply all of them to the starting value of 1.

```
// n is the only content of the stack at program start
// 1 is popped from empty stack
main = pop push-mul pop
     = n push-mul 1

// height yields 1 to n, since it is called after a push
// <a b> = a * b (where a, b are Church numerals)
push-mul = \x. <(push x) height>

```

# Answer
> 2 votes
# Japt, 1 byte

```
l

```

Try it online!

# Answer
> 2 votes
# Seriously, 2 bytes

```
,!

```

Try it online!

# Answer
> 2 votes
# Elixir, 30 bytes

Recursive.

```
def f(n),do: n>1&&n*(f n-1)||1

```

Try it online!

# Answer
> 2 votes
# T-SQL, 91 bytes

```
CREATE FUNCTION dbo.f(@ INT)RETURNS INT AS BEGIN SET @=IIF(@<=1,1,@*dbo.f(@-1))RETURN @ END

```

Demo

It seems you need to specify a schema (`dbo.`) in order to make a recursive function :( Perhaps other SQL dialects are shorter.

# Answer
> 2 votes
# ReRegex, 47 bytes

```
#import math
\b1!/1/(\d+)!/($1-1)!*$1/
#input
!

```

Defines two regexes;

`(\d+)!/($1-1)!*$1/` Looks for a base10 number followed by a !, and replaces it with `(n-1)!*n`.

`\b1!/1/` Replaces any free standing `1!`'s with just `1`.

The math library then takes care of the subtractions and multiplications. ReRegex will continue attempting its regex operations until it can no-longer modify the text.

The final two lines put the input as `n!` ready for the operations.

Values greater than 5 work offline, but due to how long they take; do not work on TIO.

Try it online!

# Answer
> 2 votes
# Perl 5 `-p`, 20 bytes

```
$\*=$_ for++$\..$_}{

```

Try it online!

# Answer
> 2 votes
# COW, 150 bytes

```
oomMOOMOoMMMmoOmoOmoOMMMMMMMoOmOomOomOoMOOmoOMMMmoOmoOMMMOOOmOoMMMmOoMOOmoOMMMMOOmoOMoOmOoMOomooMMMmOoMOomoomOoMOoMMMmoomoOmoOmoOOOMOOOMOomOOmooMoOOOM

```

Try it online!

### Commented

Four memory blocks are used. Block 1 stores a persistent counter. Blocks 2 and 3 store the temporary loop variables used for multiplication (by repeated addition). Block 4 stores the result.

```
oom                           # read input into Block 1
MOO                           # if input is not 0
  MOoMMM                        # decrement and copy
  moOmoOmoOMMMMMMMoOmOomOomOo   # paste and increment to initialise Block 4
  MOO                           # Loop 1: from Block 1 value down to 1
    moOMMM                        # set Block 2 to Block 1 value
    moOmoOMMMOOOmOoMMM            # set Block 3 to Block 4 value and zero Block 4
    mOoMOO                        # Loop 2: from Block 2 value down to 1
      moOMMMMOO                     # Loop 3: as many times as Block 3 value
        moOMoO                        # increment Block 4
      mOoMOomooMMM                  # end Loop 3
    mOoMOomoo                     # end Loop 2
  mOoMOoMMMmoo                  # end Loop 1
  moOmoOmoOOOM                  # print Block 4 value
  OOOMOomOO                     # exit
moo                           # (only get here if input is 0)
MoOOOM                        # print 1

```

# Answer
> 2 votes
# Muriel, 128 bytes

```
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";@"B:\".$(1\";a:"+~+";C:\""+|C+C

```

Try it online!

Moving another answer from the previous challenge, this time because the answer uses an `eval` function... in a language where that's the only way to loop.

This is a difficult for a number of reasons. First is Muriel itself, where the only way to do loops is to create a quine and eval it, passing a condition into the code. Next is that large numbers lose precision over time (so the output for \\$125!\\$ is `1.88267717688893e+209`), but the program can't handle that format inside the program itself, so you can't pass large numbers to the next iteration of code. The last problem is that numbers will eventually be so large, the program just renders them as `Inf`, but thankfully that's far beyond \\$125!\\$, so we don't have to worry about that.

### Explanation:

The first iteration doesn't have to be a complete quine, but can take shortcuts in constructing the actual loop.

```
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";

```

This creates an string version of the loop. This string persists across all iterations of the loop.

```
@                   # Evaluate the next strings as a new program
 "B:\".$(1\";       # Initialise B as the string ".$(1"
 a:"+~              # Initialise a as the inputted number
 +"C:\""+|C         # Initialise C as the persistent string C
 +C                 # And add the executing part of the program

```

The resulting program with input 125 looks like (newlines added for clarity)

```
B:".$(1";
a:125;
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";
@%(B+");B:\""+B+"*"+$a+"\";a:"+$(a-1)+";C:\""+|C+C),(a>0)*(&B+2),a*999+&B+2

```

The eval then executes

```
@                   # Evaluate
 %(     ...     ),(a>0)*(&B+2),a*999+&B+2   # The substring
   B+");                                    # If a is 0, evaluate B
                                            # Otherwise
   B:\""+B+"*"+$a+"\";                      # Concatonate "*a" to the end of B
   a:"+$(a-1)+";                            # Decrement a
   C:\""+|C                                 # Set C to C
   +C                                       # And add the executing part of the program

```

Eventually, `a` will reach 0, and `B` will be evaluated. B will look like:

```
.                         # Print
 $(       ...         )   # The string form of
   1*125*124*123*...*1    # The factorial

```

# Answer
> 2 votes
## Setanta, ~~45~~ ~~44~~ 43 bytes

```
gniomh F(n){ma n<2 toradh 1toradh n*F(n-1)}

```

Try it here!

# Answer
> 2 votes
# F#, 26 bytes, by Laikoni

```
fun x->List.fold(*)1[1..x]

```

Try it online!

# F#, 35 bytes

```
let rec f=function|0->1|x->x*f(x-1)

```

Try it online!

# Answer
> 2 votes
# Arn, 2 bytes

```
↓;

```

Try it!

Unpacked: `.fact`. Passes STDIN (`_`) into the factorial function via the `.` infix

## 3 byte solution:

```
A→.

```

Unpacked: `*\~`

```
  \      Fold with
*        Multiplication
    ~    1-range
      _  Variable initialized to STDIN; implied

```

# Answer
> 2 votes
# Scala 2.12, 14 bytes

```
1 to _ product

```

This is a function expression, where the underscore is the parameter. `1 to _` creates a range object, and product calculates the product of all numbers.

# Answer
> 2 votes
# Forth (gforth), 30 bytes

```
: f 1 swap 0 ?do i 1+ * loop ;

```

Try it online!

### Code Explanation

```
: f          \ start a new word definition
  1 swap 0   \ create accumulator and set up loop parameters
  ?do        \ start a conditional counted loop from 0 to n
    i 1+ *   \ multiply accumulator by loop index + 1
  loop       \ end counted loop
;            \ end word definition

```

# Answer
> 2 votes
# Labyrinth, 16 bytes

```
?+1#*
(: (;
 @!;

```

Try it online!

Utilizes two loops, one to duplicate and decrement the input until zero, then one to multiply all the items on the stack.

# Answer
> 2 votes
# Husk, 1 byte

```
Π

```

Try it online!

# Answer
> 2 votes
# ARM Thumb-2, 12 bytes

```
2101 b110 4341 3801 d1fc 4770

```

Commented assembly:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .globl factorial
        .thumb_func
        // input: r0
        // output: r1
factorial:
        // accumulator starts at 1
        movs    r1, #1
        // skip to end if r0 is zero
        cbz     r0, .Lend
.Lloop:
        // r1 *= r0
        muls    r1, r0
        // while (--r0)
        subs    r0, #1
        bne     .Lloop
.Lend:
        // return
        bx      lr

```

Standard iterative approach.

Takes a 32-bit integer in `r0`, returns a 32-bit integer in `r1`.

# ARM Thumb-2, 20 bytes

```
2201 2300 b128 fba2 2100 fb03 1300 3801 d1f9 4770

```

Commented assembly:

```
        .globl factorial64
        .thumb_func
        // input: r0
        // output: {r2, r3}
factorial64:
        // accumulator starts at 1
        movs    r2, #1
        movs    r3, #0
        // skip to end if r0 is zero
        cbz     r0, .Lend64
.Lloop64:
        // {r2, r3} *= r0
        // tmp = (u64)r2 * r0
        umull   r2, r1, r0, r2
        // {r2, r3} = tmp + (r3 * r0 << 32)
        mla     r3, r3, r0, r1
        // while (--r0)
        subs    r0, #1
        bne     .Lloop64
.Lend64:
        // return
        bx      lr

```

This version uses 64-bit arithmetic, at the cost of 8 bytes. It is only 2 more *instructions*, but two of those instructions are now wide instructions.

Takes a 32-bit integer in `r0` and returns a 64-bit integer in `{r2, r3}` (easy to forward to `printf`)

# Answer
> 2 votes
# Assembly (MIPS, SPIM), 78 bytes, 6\*9 = 54 assembled bytes

```
main:li$2,5
syscall
li$4,1
f:beqz$2,g
mul$4,$4,$2
sub$2,1
b f
g:li$2,1
syscall

```

Try it online!

This is a significant optimization of this answer, but the account was deleted.

Specifically, this makes the following changes:

* It compares once at the top of the loop, using an unconditional branch at the bottom
* It uses the numerical register names which are shorter
* It removes spaces between mnemonics, as SPIM accepts this
* It removes the second operand from `sub`

Otherwise, the logic is identical.

# Answer
> 2 votes
# Phooey, 15 bytes

```
=>&.[@<*>-1]<$i

```

Try it online!

```
=>&.[@<*>-1]<$i # stack tape
=               #   (0)  >a    0     acc = 1
 >              #   (0)   a   >0     move left
  &.            #   (0)   a   >n     read int
    [      ]    #   (0)   a   >n     loop while n != 0
     @          #    n    a   >n         push n
      <*>       #   (0)   a*n >n         multiply acc by n (popping from stack)
         -1     #   (0)   a*n >n-1       subtract 1 from n
            <   #   (0)  >res 0      go right to the result
             $i #   (0)  >res 0      print as integer

```

Since Phooey uses `int64_t`, this supports up to 20.

# Answer
> 2 votes
# Factor \+ `math.factorials`, 6 bytes

```
[ n! ]

```

Try it online!

Thanks to @Bubbler for -9 bytes

# Factor \+ `math.factorials`, 15 bytes

```
[ factorial . ]

```

Try it online!

# Answer
> 2 votes
# jq, 10 bytes

```
.+1|tgamma

```

Uses the gamma function Γ(n) = (n - 1)!

Try it online!

# Answer
> 2 votes
# Cascade, 18 bytes

```
#1]*
\aa?
(\&;
a ?

```

Try it online!

Golfed version by Jo King.

A program without `@` starts at the top-left corner. The main difference with my version is that `a` is decremented under the second branch, not first:

```
  ?
  ]
 a ?
  &;(
    a

```

---

# Cascade, 22 bytes

```
? @
]*#1
)(|a
a?\
&;a\

```

Try it online!

Solved as part of LYAL 2021-09-29.

### How it works

Cascade programs start the execution at the entry point `@`.

```
? @   The main program prints (#) the result of the huge loop
  #   starting at `?`
  |
  \
   \

 ?    (grid rotated once for clarity)
 ]    On entry, the if-clause is run:
a (   Push to the stack "a" the decrement of...
  ?   If EOF, the top value of "a", otherwise the input from stdin
 &;a

 ?    If the above is not positive, return 1;
1 *   Otherwise return (increment of a) times
 ) |  the next invocation of the main loop
 a \
\

```

# Answer
> 2 votes
# Python 3, 25 bytes

```
f=lambda n:n<1or n*f(n-1)

```

Try it online!

# Answer
> 2 votes
# Pyramid Scheme, 510 bytes

```
    ^           ^     ^
   / \         / \   / \
  /set\       /   \ /out\
 ^-----^     /loop \-----^
/a\   /]\   ^-------^   /b\
---  ^---^ /a\      -^  ---
    / \ /#\---      /]\
   /set\---^       ^---^
  ^-----^ / \     / \  -^
 /b\   ^-/   \   /set\  -^
 ---  ^-/line \ ^-----^  -^
     /1\-------/b\   ^-  / \
     ---       ---  /*\ /set\
                   ^---^-----^
                  /b\ /a\   /-\
                  --- ---  ^---^
                          /a\ /1\
                          --- ---

```

Try it online!

It works!

I spent way too long debugging this. There's a lot of empty space which I can't seem to get rid of.

This is basically the following pseudocode:

```
a = input
b = 1
while a
  b *= a
  a -= 1
print b

```

# Answer
> 2 votes
## JavaScript, 19 bytes

```
f=n=>n?f(n-1n)*n:1n

```

2 bytes longer than the other JS answers, but can safely calculate as high as 11190! instead of 18!, with anything higher exceeding the call stack size (tested on Node.js 18.6.0). the result has 40450 digits.

update: running with `--stack-size=65536` allows me to calculate up to 95200!, resulting in 432625 digits. Trying to calculate any higher caused segmentation faults, no matter what I set the stack size to.

# Answer
> 2 votes
# \>\<\>, 14 bytes

```
1$:@?!n$:1-@*!

```

Try it online

**Explanation**

```
1               # initialize product as 1
 $:@?!n         # if the current counter (starts as n) is 0, print the product
       $:1-@    # subtract 1 from the counter for the next iteration
            *   # multiply current counter with product
             !  # skip the product initialization for the next iteration

```

# Answer
> 2 votes
# Vyxal 3L, 2 bytes

```
/*

```

Try it Online!

Fold `/` the input by multiplication `*`. Fold treats whole numbers as the range from 1 to n.

The factorial built-in is 4 bytes: `fact`

# Answer
> 2 votes
# BQN, 5 bytes

```
×´1+↕

```

Try it at BQN online!

### Explanation

Same as chunes's Uiua answer, just different syntax.

```
×´1+↕
    ↕  Range from 0 to argument - 1
  1+   Add 1 to each
×´     Fold on multiplication

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 65 bytes

```
 i =input
 p =1
i x =x + 1
 p =p * x
 output =p le(i,x) :f(i)
end

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~9~~ 3 bytes

-6 bytes thanks to @att

```
#!&

```

Try it online!

# Answer
> 1 votes
# Desmos, 2 bytes

```
n!

```

Try it in Desmos

Finally a competitive Desmos answer that isn't `graphical-output`!

# Answer
> 1 votes
# MathGolf, 1 byte

```
!

```

Try it online.

**Explanation:**

```
!  # Get the factorial (aka gamma(n+1)) of the (implicit) input-integer
   # (output the entire stack joined together implicitly as result)

```

# Answer
> 1 votes
# Burlesque, 4 bytes

```
ri?!

```

Try it online!

Explanation:

```
ri    # Read integer
  ?!  # Calculate factorial

```

# Answer
> 1 votes
# Lua, 36 bytes

```
x=1 for i=1,...do x=x*i end print(x)

```

Try it online!

On Lua \<= 5.2 this will use `double`, allowing big inputs to work. On Lua 5.3+ (as currently on TIO) integers are used instead, making big inputs fail. This can be worked around at cost of one byte:

# Lua, 37 bytes

```
x=1. for i=1,...do x=x*i end print(x)

```

Try it online!

# Answer
> 1 votes
# cQuents, 5 bytes

```
$0:$!

```

Try it online!

The first three bytes are for 0-indexing, since by default cQuents uses 1-indexing.

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 30 bytes

```
int f(int n)=>n==0?1:n*f(n-1);

```

Try it online!

# Answer
> 1 votes
# PHP, 38 bytes

*Recursive...*

```
function f($n){return$n?$n*f($n-1):1;}

```

Try it online!

*Or functional...*

# PHP, 39 bytes

```
fn($n)=>$n?array_product(range($n,1)):1

```

Try it online!

# Answer
> 1 votes
# Python 2, 46 bytes

```
lambda n:reduce(lambda a,b:a*b,range(1,n+1),1)

```

How it works:

the reduce function takes in the list that contains all the numbers from 1 to n and reduces it by the multiplication function (`lambda a,b:a*b`) to a single number. An optional `initial` parameter is set in the case that `n` is equal to 0.

Try it online (with all test cases)!

# Answer
> 1 votes
# Haskell, 17 characters

```
f n=product[1..n]

```

**Bonus reference:** *"The Evolution of a Haskell Programmer"* by Fritz Ruehr

## Try it online!

# Answer
> 1 votes
# Scala 3, 79 bytes

```
import compiletime.ops.int._
type F[N<:Int]=N match{case 0=>1 case _=>N*F[N-1]}

```

Try it in Scastie

# Answer
> 1 votes
# C#, 42 bytes

Using the power of fresh and new C# 9 we can achieve a stunning 42 bytes!

```
int f(int n)=>n<2?1:n*f(n-1);return f(10);

```

for C# 8 and the online example we need to add 38 bytes for a total of 70 bytes

```
class P{static int Main(){int f(int n)=>n<2?1:n*f(n-1);return f(10);}}

```

Try it online!

# Answer
> 1 votes
# ink, 50 bytes

```
==function f(n)
{
-!n:~return 1
}
~return n*f(n-1)

```

Try it online!

Had to make it a proper function instead of just a stitch, since I actually have to use the return value (so outputting by printing is not an option - or at least not a good one).

# Answer
> 1 votes
# BRASCA v0.4, 11 bytes

v0.4 was made after my initial solution and added the `r` operator, hence the seperate answer.

```
ig0$r[*$]xn

```

Try it online!

## Explanation

```
ig          - Convert to numbers and concatenate digits
  0$r       - Push range (i, 0) to stack
     [*$]   - Multiply it all
         xn - Remove the 0 and output the result

```

# BRASCA, ~~15~~ 14 bytes

```
ig[:1-]x[*$]xn

```

Try it online!

## Explanation

```
ig                   - Convert to numbers and concatenate
  [:1-]              - Generate a sequence from N to 0 on the stack
       x             - Remove the 0
        [*$]         - Multiply it all together
            $n       - Bring the number to the front and output it

```

# Answer
> 1 votes
# Python 3, ~~30~~ 27 bytes

```
f=lambda n:1>>n or n*f(n-1)

```

Try it online!

# Answer
> 1 votes
# Kotlin, 37 bytes

```
fun a(n:Int)=(1..n).fold(1){a,b->a*b}

```

Had to use `fold(1){a,b->a*b}`(surprisingly enough 1 less byte than something like `fold(1,Int::times)`) due to a lack of a product function in the stdlib.

# Answer
> 1 votes
# Javascript (ES6),19 bytes

```
f=n=>n?f(n-1)*n:1

```

# Answer
> 1 votes
# Tcl, 35 bytes

```
proc F x {expr $x?\[F $x-1]*($x):1}

```

Try it online!

# Answer
> 1 votes
# Pxem, 26 bytes (filename) + 0 bytes (content) = 26 bytes.

* Filename (escaped): `\001._.c.w.t.m.!.m\001.-.c.a.s.n`
* Content: empty

## Usage

* Input decimal integer from STDIN
* Output to STDOUT

## How it works

```
XX.z
.a\001XX.z # push one
.a._.c.wXX.z # push getint; dup; while pop!=0; do
  .a.t.m.!XX.z # heap=pop; push heap; push pop*pop
  .a.m\001.-XX.z # push heap; push 1; push abs(pop-pop)
  .a.cXX.z # dup
.a.a.s.nXX.z # done; pop; printf "%d" pop
.a

```

Try it online!

# Answer
> 1 votes
# M4, 49 bytes

```
define(f,`ifelse($1,0,1,`eval($1*f(decr($1)))')')

```

Try it online!

## Usage

```
f(n)dnl where n is an integer.

```

# Answer
> 1 votes
# Python 3, 56 bytes

```
def f(n):
 k=1
 for i in range(2,n+1):
  k=k*i
 return k

```

Try it online!

# Answer
> 1 votes
# Pinecone, 45 bytes

```
f::{Int}:(k:1;i:1|i<=in|i:i+1@k:k*i;print:k)

```

# Answer
> 1 votes
# Red, 40 bytes

```
f: func[n][either n = 0[1][n * f n - 1]]

```

Try it online!

I'm surprised there are no Red answers here yet. I'm still pretty new to Red, so there may be golf potential here. But I condensed it as much as I could (all the whitespace is necessary). It's the simple recursive definition: if n = 0, return 1, else return n * f(n-1).

# Answer
> 1 votes
# Wren, 36 bytes

```
var F=Fn.new{|n|n<1?1:n*F.call(n-1)}

```

Try it online!

# Answer
> 1 votes
# Cubix, 24 bytes

```
I:;.^!^u.>($.sr*u..;uO;@

```

Try it online!

And here's a link to the Cubix online interpreter you can run in "debug" mode if you want to see the IP as it moves around the cube the code on.

http://ethproductions.github.io/cubix/?code=STo7Ll4hXnUuPigkLnNyKnUuLjt1TztA&input=NgoK&speed=6

I find it hard to explain code in this language, since the directions the code takes a confusing (since it's running through code wrapped around a cube). The size of the cube used varies based on the length of the code. In this case each side has 4 characters.

Here goes...

```
I:;.^!^u.>($.sr*u..;uO;@
    ^                    - code starts here, change IP to "up"
I:                       - read a number from STDIN, duplicate it on stack
         >               - change IP to "right" (start of loop)
          (              - decrement top of stack
           $             - skip the next instruction
    ^                    - SKIPPED
     !                   - if top of stack not 0, skip next instruction
      ^                  - TRUE, change IP to "up" (exit path 0)
       u                 - FALSE, IP does a "u turn"
               *         - multiple top two entries on the stack
              r          - rotate top three stack entries twice
             s           - flip the top two entries on the stack
                   ;     - delete the top of stack
                u        - IP does a "u turn", (end of loop)
  ;                      - exit path 1, delete top of stack
I                        - exit path 2, read STDIN as number onto stack
           $             - exit path 3, skip next instruction
                   ;     - exit path 4, SKIPPED
                      ;  - exit path 5, delete top of stack
                    u    - exit path 6, IP makes a "u turn"
                     O   - exit path 7, output top of stack as a number
                       @ - exit path 8, halt program

```

# Answer
> 1 votes
# Python 3, 31 bytes

```
f=lambda n:n>1 and n*f(n-1)or 1

```

Try it online!

# Answer
> 1 votes
# Rattle, 14 bytes

```
|F0:s[1F]-F0*~

```

Try it Online!

There's already a Rattle answer here by me but this approach is completely different. Not only does this answer use the shiny new interpreter, but it takes advantage of the fact that recursion was recently implemented in Rattle!

# Explanation

```
|                parses the user's input
 F0              calls local function 0
   :             (separator between the main method and local function 0)
    s            save the current value to local memory slot 0 (local to only this instance of F0)
     [1 ]        if the value is equal to 1, then:
       F         return (returns 1)
         -       subtract 1 from the current value
          F0     recursively call function 0 with the current value as a parameter
            *~   multiply the result of function 0 by the value stored in local memory
                 (the result of the multiplication is returned)

```

Rattle is able to process factorials up to `170!` with no loss in precision.

# Answer
> 1 votes
# Knight, 28 bytes

```
;;;=xP=y 1W<0=x-x 1=y*y+1xOy

```

Try it online!

# Answer
> 1 votes
# Knight, 26 bytes

```
;=yT;=x+0P;W=x-xT=y*+xTyOy

```

Try it online!

# Answer
> 1 votes
# StackCell, 14 bytes

Uses this input format and this output format

The below code uses the Unicode control character glyphs \[U+24XX\] to represent ASCII unprintable control characters embedded in the source code

\[the input is implicitly pushed to the stack before the program begins\]

```
{'␁}[}*'␁}-{}]

```

\[the output is left as the sole value on the stack after the program ends\]

For standard I/O (i.e. stdin and stdout), the following snippet can be used to place the input on the stack (for 21 bytes):

```
'0'␁['0x-x'
*+@:'
-]`

```

and for output (26 bytes):

```
:[:'
x%'0+{X}X'
x/:]X:[:;]

```

For the complete program using stdin/stdout only, that means a total of 61 bytes:

```
'0'␁['0x-x'
*+@:'
-]`{'␁}[}*'␁}-{}]:[:'
x%'0+{X}X'
x/:]X:[;:]

```

# Answer
> 1 votes
# Carbon, 53 bytes

```
fn f(x:i32)->i32{return if(x==0)then 1else x*f(x-1);}

```

Try it Online!

Here is a full program for testing at the above site:

```
package c api;

fn f(x:i32)->i32{return if(x==0)then 1else x*f(x-1);}

fn Main() -> i32 {
  return f(5);
}

```

# Answer
> 1 votes
# Arturo, 9 bytes

```
factorial

```

Try it

Builtin

# Arturo, ~~18~~ 12 bytes

```
$=>[∏1..&]

```

Try it

Non-builtin

# Answer
> 1 votes
# Clojure, 38 bytes

```
(defn f[n](apply *' (range 2(inc n))))

```

Try it online!

# Answer
> 1 votes
# Thunno, \\$ 1 \log\_{256}(96) \approx \\$ 0.82 bytes

```
F

```

Attempt This Online! or verify \\$0!\\$ to \\$10!\\$.

Builtins FTW.

# Answer
> 1 votes
# Pyt, 1 byte

```
!

```

Try it online!

Builtins FTW.

# Answer
> 1 votes
# All answers works correctly for `0` only in Firefox

# JavaScript, 29 bytes

* Without recursion
* Expects `Number` type
* Max value is `170`. If above outputs `Infinity`

```
n=>eval('p=1;while(n)p*=n--')

```

```
f=n=>eval('p=1;while(n)p*=n--')

;[
  0, // 1
  1, // 1
  2, // 2
  3, // 6
  4, // 24
  5, // 120
  6, // 720
  7, // 5040
  8, // 40320
  9, // 362880
  10, // 3628800
  11, // 39916800
  12, // 479001600
  170, // 7.257415615308004e+306
  171, // Infinity
].forEach(n=>document.write(n + ' - ' + f(n), '<br>'))
```

# JavaScript, 30 bytes

* Without recursion
* Expects `BigInt` type
* In theory there is no max value. In practice it depends on implementation

```
n=>eval('p=1n;while(n)p*=n--')

```

```
f=n=>eval('p=1n;while(n)p*=n--')

;[
  0n, // 1
  1n, // 1
  2n, // 2
  3n, // 6
  4n, // 24
  5n, // 120
  6n, // 720
  7n, // 5040
  8n, // 40320
  9n, // 362880
  10n, // 3628800
  11n, // 39916800
  12n, // 479001600
  170n, // 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000
  171n, // 1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000
].forEach(n=>document.write(n + ' - ' + f(n), '<br>'))
```

# JavaScript, 33 bytes

* Without recursion
* Expects `Number` or `BigInt` type
* Max value for type `Number` is `170`. In theory there is no max value for type `BigInt`

```
n=>eval('p=++n/n;while(--n)p*=n')

```

```
f=n=>eval('p=++n/n;while(--n)p*=n')

;[
  0, // 1
  1, // 1
  2, // 2
  3, // 6
  4, // 24
  5, // 120
  6, // 720
  7, // 5040
  8, // 40320
  9, // 362880
  10, // 3628800
  11, // 39916800
  12, // 479001600
  170, // 7.257415615308004e+306
  171, // Infinity
  0n, // 1
  1n, // 1
  2n, // 2
  3n, // 6
  4n, // 24
  5n, // 120
  6n, // 720
  7n, // 5040
  8n, // 40320
  9n, // 362880
  10n, // 3628800
  11n, // 39916800
  12n, // 479001600
  170n, // 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000
  171n, // 1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000
].forEach(n=>document.write(n + ' (' + typeof n + ') - ' + f(n), '<br>'))
```

# Answer
> 1 votes
# Nibbles, 8 nibbles (4 bytes)

```
? $ `*,$ 1

```

Attempt This Online!

## Explanation

```
? $ `*,$ 1    #
----------------------------------------
? $           # if arg1
              # equals truthy (<0)
    `*        #    product
      ,$      #    range 1..arg1
              # else
         1    #    1

```

# Answer
> 1 votes
# Julia 1.0, 9 bytes

```
factorial

```

Try it online!

## 12 bytes

```
~x=*(1:x...)

```

Try it online!

```
~x=prod(1:x)

```

Try it online!

# Answer
> 1 votes
# vemf, 1 byte

```
!

```

Falls back to \\$\Gamma\left(\alpha+1\right)\\$ if \\$\alpha\notin\mathbb Z\\$

In the online interpreter this works (returns values other than /`0`/`-0`/`inf`) for \\$-178.9999999999999\le\alpha\le170.6243769563\\$ and \\$\alpha\notin\mathbb Z^-\\$ (set of negative integers)

# Answer
> 1 votes
# minigolf, 6 bytes

```
1i,n*_

```

Attempt This Online!

## Explanation

```
1      Push 1
i      Push input
,      Repeat input times ([1..n]):
  n*     Muliply tos by curr. item
_      end repeat

implicit output

```

# Answer
> 1 votes
# Swift, ~~37~~ 36 bytes

```
var f={$0<1 ?1:(1...$0).reduce(1,*)}

```

Self-explanatory. Call it as `f(n)`.

# Answer
> 1 votes
# Itr, 2 bytes:

`#P`

online interpreter

The product over the range from 1 to the input number

# Answer
> 1 votes
# Gema, 41 characters

```
f:*=@cmpi{*;0;;1;@mul{@f{@sub{$0;1}};$0}}

```

Assuming a domain can be considered equivalent of a function.

(Being pure text processing utility, no way to calculate up to 125! to qualify for the old challenge.)

Sample run:

```
bash-5.2$ gema '*=@f{*};f:*=@cmpn{*;0;;1;@mul{@f{@sub{$0;1}};$0}}' <<< 12
479001600

```

Try it online!

# Answer
> 0 votes
# PPL, 60 bytes

```
fnf(n){
declarea=1
declares=1
loopn{
a=a*s
s=s+1
}
returna
}

```

Anybody remember **PPL**? ;)

Declares a new function f with variables `a` and `s`. Loops `n` times and multiplies a by s each time.

Sadly recursion is not supported with PPL.

# Answer
> 0 votes
# APOL, 24 bytes

`⊕(ƒ(-(⧣ 1) *(⋒ -(⋒ ∈))))`

Explanation:

```
⊕(         Sum of list
  ƒ(        List-builder for
    -(      Subtract
      ⧣     Integer input
      1
    )
    *(      Multiply
      ⋒     For iterator (what's being iterated through)
      -(    Subtract
         ⋒  For iterator
         ∈  Loop counter
      )
    )
  )
)

```

# Answer
> 0 votes
# Fortran (GFortran), ~~51~~ 42 bytes

We abuse that variables (and functions) beginning with i,j,k,l,m or n are assumed to be (or return) integers, and that all other objects are assumed to be (or return) reals to create this function that generates a list of integers and multiplies them together into a another integer. It breaks at i=13.

```
function k(i)
k=product((/(j,j=1,i)/))
end

```

Try it online!

# Answer
> 0 votes
## Python, ~~34~~ 29 Bytes

```
x=lambda a:a and a*x(a-1)or 1

```

`lambda` is good at shortening code!
-5 from TheThonnu

# Answer
> 0 votes
# Python, 26 Bytes

```
import math
math.factorial

```

Uses the built-in function from the built-in module `math`.

# Answer
> 0 votes
# Thunno 2, 1 byte

```
w

```

Attempt This Online! Built-in.

## Thunno 2, 2 bytes

```
Rp

```

Attempt This Online! Product of range.

# Answer
> 0 votes
# Desmoslang Assembly, 3 Bytes

```
I!OT

```

Explanation: Takes input to Command, adds an exclamation mark for factorial, outputs it, and loops infinitely at the end.

# Answer
> 0 votes
# Thue++, 43 bytes

```
^(x*)x!::=$1!/$1
^((!+)/+x*)x::=$1$2
/!::=!

```

Input is on the state, in the form of some number of xs followed by an exclamation mark, output is on the state in the form of a number of exclamation marks.

Alternate idea that I'm not sure if allowed because the output has a number of slashes that arent part of the output total, 37 bytes:

```
^(x*)x!::=$1!/$1
^(([/!]+)x*)x::=$1$2

```

# Answer
> 0 votes
## HP‑41C series, 1 B

Place \\$n\\$ into the `X` register (that is the top of the stack) and `XEQ` (execute) the built‑in command

```
FACT

```

\\$n!\\$ is now in the `X` register and \\$n\\$ in the `L` (“last `X`”) register. The operation reports a `DATA ERROR` in case of negative or non‑integral arguments, and an `OUT OF RANGE` error for \\$n \ge 70\\$.

You can *ignore* “out of range” errors by setting flag 24 (`SF 24`). If flag 24 is set, the operation is successful and yields 9.999999999 × 1099 as an “approximation”.

# Answer
> 0 votes
# \[Assembly (nasm, x64, Linux)\], 103 bytes

```
4c89c0e84a0000006683f800770366ffc048be0000000000000000b90a00
00004831d2f7f180c23066ffce88166683f80075ed66ffc066bf010048ba
00000000000000004829f20f0549ffc04983f80d7cae5083f801740c66ff
c8e8f2ffffff48f724244159c3

```

Try it online!

**How it works**

fact.asm

```
c:mov rax,r8
call f          ; <---- Call factorial f()
cmp ax,0
ja x
inc ax
x:mov rsi,n     ; <---+
mov ecx,10      ;     |
l:xor rdx,rdx   ;     |
div ecx         ;     | Convert factorial to ASCII
add dl,48       ;     |
dec si          ;     |
mov[rsi],dl     ;     |
cmp ax,0        ; <---+
jnz l
inc ax          ; <---+
mov di,1        ;     |
mov rdx,n+1     ;     | Write factorial to stdout
sub rdx,rsi     ;     |
syscall         ; <---+
inc r8
cmp r8,13       ; <---- Loop [0,12]
jl c
f:push rax      ; <---+
cmp eax,1       ;     |
jz e            ;     |
dec ax          ;     | Compute factorial EAX (in/out)
call f          ;     |
mul qword[rsp]  ;     |
e:pop r9        ;     |
ret             ; <---+
section .data
resb 9
n: db 10

```

**Build Commands**

```
nasm -f elf64 fact.asm -o fact.o
ld fact.o -o fact
objcopy --dump-section .text=text.bin fact.o
xxd -p text.bin > text.hex

```

# Answer
> 0 votes
## Pascal, 27 B

The source code is split into a left half containing the boilerplate for a complete Pascal `program`, and right half containing the necessary step to *evaluate* \\$n!\\$ (i. e. the task). Only the *extra* bytes necessary to achieve *the task* are counted.

```
{ boilerplate                          }{ necessary for evalution      }
program factorial(input, output);
    var
        n                               ,i
        :integer;
    begin
          readLn(input,  n);            for i≔2 to n−1 do n≔i*n
        ;writeLn(output, n)
    end.

```

The built‑in data type `integer` comprises (at least) the range `−maxInt` through `+maxInt` inclusive. The value of the built‑in constant `maxInt` is *implementation‑defined*. Today, it is usually \\$2^{63}-1\\$, so you can calculate up to \\$20!\\$.

Remember that in Pascal `for`‑loop limits are *inclusive*, so you subtract \\$1\\$ from \\$n\\$. This is similar to the limits in mathematical notation \\$\prod\\$ and \\$\sum\\$.

# Answer
> -3 votes
# Python + `sympy`, 94 Bytes

```
from sympy import *
x=Symbol("x")
i=int(input())
e=x**i
for y in range(i):
 e=diff(e)
print(e)

```

Requires you to do `pip install sympy` in the command prompt, as this isn't a built-in module. Uses a calculus approach to calculate factorials.

---
Tags: code-golf, math, arithmetic, factorial
---