58
\$\begingroup\$

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.

\$\endgroup\$

161 Answers 161

2
\$\begingroup\$

jq, 10 bytes

.+1|tgamma 

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

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think |ceil is not necessary since floating point imprecision is allowed. \$\endgroup\$ Commented Sep 2, 2021 at 23:50
2
\$\begingroup\$

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 \ \ 
\$\endgroup\$
2
\$\begingroup\$

Python 3, 25 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This does not work. This outputs True for 0 when it should output 1. You can fix this by replacing n<1 with +(n<1) to cast it to an integer. You can also remove f= to save 2 bytes. \$\endgroup\$ Commented Aug 24, 2023 at 9:42
  • \$\begingroup\$ @TheEmptyStringPhotographer thanks for your feedback! In Python, True == 1, so it is generally accepted to leave it at that. Also, the f= is required because the lambda is recursive. \$\endgroup\$ Commented Aug 31, 2023 at 13:25
2
\$\begingroup\$

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 
\$\endgroup\$
2
\$\begingroup\$

><>, 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 
\$\endgroup\$
2
\$\begingroup\$

Nibbles, 8 nibbles (4 bytes)

? $ `*,$ 1 

Attempt This Online!

Explanation

? $ `*,$ 1 # ---------------------------------------- ? $ # if arg1 # equals truthy (<0) `* # product ,$ # range 1..arg1 # else 1 # 1 
\$\endgroup\$
1
  • \$\begingroup\$ Golfing tip: The product of an empty list is 1 in a lot of languages, including Nibbles, so the if-not-zero logic isn't needed. \$\endgroup\$ Commented Apr 22, 2024 at 3:26
2
\$\begingroup\$

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 
\$\endgroup\$
2
\$\begingroup\$

Setanta, 45 44 43 35 bytes

gniomh F(n){toradh(n>1&n*F(n-1))|1} 

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Desmos, 2 bytes

n! 

Try it in Desmos

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

\$\endgroup\$
1
\$\begingroup\$

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) 
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 4 bytes

ri?! 

Try it online!

Explanation:

ri # Read integer ?! # Calculate factorial 
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

cQuents, 5 bytes

$0:$! 

Try it online!

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

\$\endgroup\$
1
\$\begingroup\$

C# (Visual C# Interactive Compiler), 30 bytes

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

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Suggest n<1 instead of n==0 \$\endgroup\$ Commented Aug 31, 2020 at 9:36
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ If anyone knows if there's a way to do 7.4 arrow functions with recursion I'd be very interested to know! \$\endgroup\$ Commented Aug 25, 2020 at 19:24
1
\$\begingroup\$

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

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

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!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Python 3, 30 27 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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 
\$\endgroup\$
1
\$\begingroup\$

Javascript (ES6),19 bytes

f=n=>n?f(n-1)*n:1 
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think there is a typo in your code. That will always return 1. \$\endgroup\$ Commented Feb 12, 2021 at 14:13
  • \$\begingroup\$ @EasyasPi My bad, forgot to multiply. Works now. \$\endgroup\$ Commented Feb 12, 2021 at 21:33
1
\$\begingroup\$

Tcl, 35 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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. 
\$\endgroup\$
1
\$\begingroup\$

Python 3, 56 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! \$\endgroup\$ Commented Apr 16, 2021 at 16:25
1
\$\begingroup\$

Pinecone, 45 bytes

f::{Int}:(k:1;i:1|i<=in|i:i+1@k:k*i;print:k) 
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.