# The vanilla factorial challenge

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.

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

• It may be a terrible language, but it's fun. :) Nov 12, 2021 at 10:52

# jq, 30 bytes

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


Try it online!

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.

• Nice! Can you please do another answer, as I can't start a +50 bounty on this because I've answered this question. Sep 2, 2021 at 20:40
• @emanresuA yeah, I noticed your js answer so I didn't bold it. I'll notify when i post my next one. Sep 3, 2021 at 2:32

# 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



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

# Ruby, 23 19 bytes

->n{Math.gamma n+1}


-4 bytes using gamma function (Dingus).

Try it online!

seq -s* $1|bc  Try it online! • Hopefully you don't have a filename beginning with -s in the current directory. Aug 25, 2020 at 9:58 # Python 2, 38 bytes i=n=1;exec"n*=i;i+=1;"*input();print n  Try it online! • Nice attempt. Note that the old challenge has a ton of non-builtin Python answers, the best being a 25-bytes function. Aug 25, 2020 at 8:18 • @Bubbler I just wanted to see what I could get without looking at the old ones Aug 25, 2020 at 8:19 • Nice, your exec this beats the while loop: TIO – xnor Aug 25, 2020 at 9:57 # 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. # 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! • Doesn't simply f n=product[1..n] work for 17 bytes? Aug 26, 2020 at 21:43 # Pepe, 57 bytes 3 bytes have been decreased from my Pepe factorial program. rrEEReREEEEErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE  Try it online! # 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! # 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)!)  # 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 :) • The recursive version should include the part that makes it a named function f, because the submission wouldn't work without it. So it is 49 bytes. Feb 15, 2021 at 3:32 • and you can save some bytes Try it online! Feb 15, 2021 at 5:47 • recursive via filter Try it online! Feb 15, 2021 at 11:25 • and filter f{$_ ?$_*(--$_|f):1} (27 bytes) with ternary operator for PS7 Feb 15, 2021 at 11:30

# Python 3, 6150 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.

• You can remove the variable x and just use a*=i+1. And then you can write the for loop on a single line as for i in range(n):a*=i+1. Nice first answer. Also check out Tips for golfing in Python. May 11, 2021 at 2:32
• Also since n is used only once, you can pass int(input()) to range(...) directly. Try it online! May 11, 2021 at 2:35
• You can move the a*=i+1 to the same line as the for loop to save 2 bytes
– Jo King
May 11, 2021 at 5:39

# Rockstar, 7066626160 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)

• Say F to Pay Respects Sep 9, 2020 at 16:07
• I'm tempted to rename F to X... Sep 10, 2020 at 1:58

# 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
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
\/     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


# Piet, 6×9 = 54 pixels (107 bytes)

Try it online!

Golfed version of Thomas Polasek's factorial program in Piet's samples page.

# 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".

# Pyth, 2 bytes

*F


Try it online!

Alternate solution:

.!


# 05AB1E, 1 byte

!


Try it online!

# Python 3.8, 23 21 bytes

Saved 2 bytes thanks to Bubbler!!!

import math
math.perm


Try it online!

• I think f= can be excluded from the byte count? Aug 24, 2020 at 23:44
• @Bubbler You get so used to things you forget what their orginal purpose was - thanks for the heads up! :D Aug 24, 2020 at 23:55
• What's the point of the math.perm line? I mean, sure, we use math.perm() in the footer, but you can take out that math.perm line and the code will still work. (Then again, maybe the import math line can just be placed in the header, which would leave... 0 bytes? Hm... maybe we should count math.perm.)
– J-L
Aug 25, 2020 at 17:41
• @J-L In function answers the whole point is to provide enough code to define a function that solves the challenge. Here the function is math.perm so job done. Leaving anything out doesn't provide a full solution. Aug 25, 2020 at 17:52
• Hmm I feel like excluding the f= is somehow wrong, maybe because the interface between the answer and the evaluation code is tightly coupled? Moving f= to the header only makes sense when the first line of code can be used as an expression without assignment, in this case we could wrap math.perm in a lambda and then import math to fit the usual pattern of excluding the assigned variable. If math.perm is allowed to be named in the evaluation code, we could look at the import math statement as a complete solution since it defines math.perm in the current scope. Feb 7 at 4:56

# Japt, 1 byte

l


Try it online!

# 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


# Elixir, 30 bytes

Recursive.

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


Try it online!

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

# 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!

# Perl 5-p, 20 bytes

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


Try it online!

• Alternatively, for 20 bytes as well: $;=$_;$_*=$;while--$ ;-) – Dada Aug 25, 2020 at 15:13 • Nice to see you back around @Dada! Aug 25, 2020 at 15:15 • $_*="@F"while--$F[0] too (with -a)... there must be something shorter! Aug 25, 2020 at 15:17 • Oh, those don't work with 0 :( Aug 25, 2020 at 15:29 • Indeed, I didn't noticed that :x – Dada Aug 25, 2020 at 15:32 # 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

• @640KB Sorry for the late response, it's fixed now.
– user96495
Aug 26, 2020 at 1:17

# 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



# 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