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

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


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

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

# 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. # Factor + math.factorials, 6 bytes [ n! ]  Try it online! Thanks to @Bubbler for -9 bytes # Factor + math.factorials, 15 bytes [ factorial . ]  Try it online! • There's n! which is a synonym of factorial, and you don't need to print the result, so simply n! is a valid built-in submission. (You don't need to wrap it in a quotation, as a built-in submission is scored by its name.) Mar 31 at 3:34 # 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! # jq, 10 bytes .+1|tgamma  Uses the gamma function Γ(n) = (n - 1)! Try it online! • I think |ceil is not necessary since floating point imprecision is allowed. Sep 2 at 23:50 # 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  # Keg, -hr, 4 bytes Ï_∑*  Try it online! # 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! # Io, 20 bytes method(\,\factorial)  Try it online! # Seriously, 2 bytes ,!  Try it online! # Desmos, 2 bytes n!  Try it in Desmos Finally a competitive Desmos answer that isn't graphical-output! # Wolfram Language (Mathematica), 9 3 bytes -6 bytes thanks to @att #!&  Try it online! • 3 bytes – att Aug 25 '20 at 5:00 # 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)  # Elixir, 30 bytes Recursive. def f(n),do: n>1&&n*(f n-1)||1  Try it online! # Burlesque, 4 bytes ri?!  Try it online! Explanation: ri # Read integer ?! # Calculate factorial  # 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! # cQuents, 5 bytes $0:$!  Try it online! The first three bytes are for 0-indexing, since by default cQuents uses 1-indexing. # C# (Visual C# Interactive Compiler), 30 bytes int f(int n)=>n==0?1:n*f(n-1);  Try it online! • Suggest n<1 instead of n==0 Aug 31 '20 at 9:36 # 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!

• If anyone knows if there's a way to do 7.4 arrow functions with recursion I'd be very interested to know! Aug 25 '20 at 19:24

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

• You can do -~b to just do range(n). You've also got a trailing space in your submission
– Jo King
Aug 27 '20 at 6:08
• If you didn't notice yet, TIO has a Code Golf submission generator. Aug 28 '20 at 2:26

# Haskell, 17 characters

f n=product[1..n]


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

# 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


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

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

# Husk, 1 byte

Π


Try it online!

# Python 3, 30 27 bytes

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


Try it online!

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

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

• OMG, you beat x86-16?!
– user99151
Feb 11 at 7:07