33
\$\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\$

94 Answers 94

1 2 3
4
0
\$\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\$
0
\$\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\$
0
\$\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\$ – Makonede Apr 16 at 16:25
0
\$\begingroup\$

Pinecone, 45 bytes

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.