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

114 Answers 114

1 2 3
4
1
\$\begingroup\$

Husk, 1 byte

Π

Try it online!

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

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)

\$\endgroup\$
1
  • \$\begingroup\$ OMG, you beat x86-16?! \$\endgroup\$
    – user99151
    Feb 11, 2021 at 7:07
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\$
    – EasyasPi
    Feb 12, 2021 at 14:13
  • \$\begingroup\$ @EasyasPi My bad, forgot to multiply. Works now. \$\endgroup\$
    – emanresu A
    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\$
    – Makonede
    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\$

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

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

Python 3, 31 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Nov 15, 2021 at 15:54
  • \$\begingroup\$ Make sure to check out our tips for golfing in Python to see if there are any ways to golf your program. I don't have much experience golfing Python myself, but I did notice that you can remove a space for 30 bytes. \$\endgroup\$ Nov 15, 2021 at 16:01
1
\$\begingroup\$

Knight, 28 bytes

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

Try it online!

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

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.

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

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!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Python 3, 25 bytes

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

Try it online!

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

Wren, 36 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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