69
\$\begingroup\$

Create the shortest program or function that finds the factorial of a non-negative integer.

The factorial, represented with ! is defined as such

$$n!:=\begin{cases}1 & n=0\\n\cdot(n-1)!&n>0\end{cases}$$

In plain English the factorial of 0 is 1 and the factorial of n, where n is larger than 0 is n times the factorial of one less than n.

Your code should perform input and output using a standard methods.

Requirements:

  • Does not use any built-in libraries that can calculate the factorial (this includes any form of eval)
  • Can calculate factorials for numbers up to 125
  • Can calculate the factorial for the number 0 (equal to 1)
  • Completes in under a minute for numbers up to 125

The shortest submission wins, in the case of a tie the answer with the most votes at the time wins.

\$\endgroup\$
  • 9
    \$\begingroup\$ How many of the given answers can actually compute up to 125! without integer overflow? Wasn't that one of the requirements? Are results as exponential approximations acceptable (ie 125 ! = 1.88267718 × 10^209)? \$\endgroup\$ – Ami Feb 6 '11 at 22:43
  • 6
    \$\begingroup\$ @SHiNKiROU, even golfscript can manage 125! less than 1/10th of a second and it's and interpreted interpreted language! \$\endgroup\$ – gnibbler Feb 8 '11 at 3:21
  • 5
    \$\begingroup\$ @ugoren the two-character solution to the other question uses a built-in factorial function. That's not allowed in this version of the challenge. \$\endgroup\$ – Michael Stern Jan 7 '14 at 3:18
  • 3
    \$\begingroup\$ Completes in under a minute seems a very hardware-dependent requirement. Completes in under a minute on what hardware? \$\endgroup\$ – sergiol Aug 24 '17 at 18:05
  • 3
    \$\begingroup\$ @sergiol Incredibly that hasn't been an issue in the last 2 years, I suspect most languages can get it done in under a minute. \$\endgroup\$ – Kevin Brown Aug 24 '17 at 21:20

173 Answers 173

0
\$\begingroup\$

Tcl, 41 37 35 bytes

proc f n {expr $n?($n)*\[f $n-1]:1}

Try it online!

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

TI-BASIC (noncompeting), 22 13 bytes

prod(seq(X+not(X),X,0,Ans

Note that on the calculator, prod(, seq(, not(, etc. are each one byte.

Can only handle inputs up to 69 without overflowing; hence, noncompeting.

Thanks to Timtech for the +not(X) idea!

Usage:

0:prgmF:Ans
               1
10:prgmF:Ans
         3628800
\$\endgroup\$
0
\$\begingroup\$

Recursiva, 12 bytes

=a0:1!*a#~a$

Try it online!

Explanation:

=a0:1!*a#~a$
=a0:1        - If a==0 return 1
     !       - Else
      *      - Multiply
       a     - a
        #~a$ - Call self but with parameter a-1
\$\endgroup\$
0
\$\begingroup\$

Axiom, 42 31 bytes

h x==(x=0=>1;product(i,i=1..x))

The 42 bytes one

s(x)==(x=0=>1;reduce(*,[j for j in 1..x]))

There could be even the 37 bytes

f(x)==(x=0=>1;reduce(*,expand(1..x)))

but there is one warning when I use it the first time

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

Brainfuck, 109 Bytes

>>>,[[<<<+>>+>>+<-]>-[<+>-]<<<<-[>>[>[>+>+<<-]>>[<<+>>-]<<<-]<<-[>+>+<<-]>[<+>-]>>[-]>[<+>-]<<<<]>>[->+<]<<]+

The factorial is left on the tape at position 4, user input is taken as an ASCII character. Meets all requirements except for completing in under a minute.

How it works:

>>>,

Gets user input and stores it in position 4. The rest of the code is in brackets to account for an input of zero. In that case, none of the following code is executed, and it skips to the last command.

[<<<+>>+>>+<-]

Move the input number to positions 1, 3, and 5.

>-[<+>-]

Decreases the number at 5, and moves it to 4.

<<<<-

Decrease the number at 1. This serves as a counter for how many times we need to multiply

This is where most of the work occurs:

[                | While 1 is non-zero (n-1 times)
  >>[            | Move to 3, and while it's non-zero
    >[           | Move to 4
      >+>+<<-    | Copy it into 5 and 6
    ]>>          | Move to 6
    [            |
      <<+>>-     | Copy it to 4
    ]<<<-        | Move to 3, decrease it
  ]<<-           | Move to 1, decrease it (one multiplication has been done)
  [              |
    >+>+<<-      | Copy the value at 1 to 2 and 3
  ]>             | Move to 2
  [              |
    <+>-         | Put it back in 1
  ]>>            | Go to 4
  [-]            | Zero it
  >[             | Go to 5
    <+>-         | Copy 5 to 4
  ]              |
<<<<]            | Go back to 1

For values >1, we could end here, but for 1:

>>[->+<]<<]

No multiplications will have been done, and we'll have a 1 in position 3. If this is the case, move it to 4. Return to 1.

]+

If the input was 0, put a one in the current position (4, since we never moved)

\$\endgroup\$
  • \$\begingroup\$ Thought I'd let you know I made a much shorter answer, almost halving your byte count \$\endgroup\$ – Jo King Nov 24 '17 at 9:51
0
\$\begingroup\$

Javascript (No body version), 23 bytes

f=(n,t=n?n*f(n-1):1)=>t

Saved 2 bytes with n?n, got the idea from Drew Christensen. This is what I had before

f=(n,t=0**n||n*f(n-1))=>t

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

4, 37 bytes

3.70060101602018002010100100000295014

Try it online!

If you question the input method, please visit first the numerical input and output may be given as a character code meta post.

Pseudo code

g_0 = input()
g_1 = 1
while g_0 != 0:
  g_1 *= g_0
  g_0 -= 1
print(g_1)
\$\endgroup\$
0
\$\begingroup\$

Forth (gforth), 31 bytes

: f 1e 0 ?do i 1+ s>f f* loop ;

Try it online!

Answer will be on the floating point stack as 125! exceeds the maximum double precision integer value (by a lot)

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

Stax, 4 bytes

┤c5ô

Run and debug it online

Unpacked version with 5 bytes:

!x+k*

Explanation

!x+      Compute logical not, then add to itself
             The result is denoted `m`
   k*    reduce with multiplication over the range [1..m]
\$\endgroup\$
0
\$\begingroup\$

Gol><>, 8 bytes

1IFLP*|h

Try it online!

How it works

1IFLP*|h

1         Push 1
 I        Take input (n) as int
  F   |   Repeat n times...
   LP*      Multiply loop counter(L) + 1; L = 0..n-1
       h  Print the top as int and halt

Function form, 8 bytes

Assuming that stack input and stack output are allowed for Gol><> functions.

1$FLP*|B

Try it online!

Takes the stack as input (assuming the stack has only one value), and leaves the factorial as the only content of the stack. $ is used to push 1 to the bottom, and B is the "return" command. Note that B inside an F (for) or W (while) loop acts as a "break" instead.

Using the Gol><> function

The following code uses the function above to output 0! to 125!.

1AG`~FLGN|;
1$FLP*|B

1AG          Register row 1 as function G
   `~        126
     F   |   Repeat from 0 to 125...
               Stack is empty at this point
      L        Push loop counter
       G       Call G on the current stack
        N      Pop and print as number, with newline
          ;  Halt
\$\endgroup\$
0
\$\begingroup\$

dc, 22 bytes

[1q]sg[d2>gd1-d2<f*]sf

Try it online! (requires Javascript)

This is the obvious 12-byte implementation ([d1-d1<f*]sf) with an additional test to short-circuit the calculation for numbers less than 2 (which otherwise subtract too far, yielding a product of zero).

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

Java (JDK 10), 84 bytes

n->{var r=java.math.BigInteger.ONE;for(;n>0;)r=r.multiply(r.valueOf(n--));return r;}

Try it online!

Credits

\$\endgroup\$
  • 1
    \$\begingroup\$ You can save 5 bytes by using Java 9's var and removing the r=null initialisation: n->{var r=java.math.BigInteger.ONE;for(;n>0;)r=r.multiply(r.valueOf(n--));return r;} \$\endgroup\$ – mgthomas99 Sep 11 '18 at 21:45
  • 2
    \$\begingroup\$ @mgthomas99 Indeed! But it's Java 10's var, not Java 9's ;) and it wasn't released at the time I wrote that answer. But I have no issue switching to Java 10. \$\endgroup\$ – Olivier Grégoire Sep 12 '18 at 7:48
0
\$\begingroup\$

Japt, 4 bytes

oÄ ×

Try it


Explanation

o        :Range [0,input) (= empty array when input is 0)
 Ä       :Add 1 to each
   ×     :Reduce by multiplication, with an initial value of 1
\$\endgroup\$
0
\$\begingroup\$

Symbolic Python, 36 bytes

__('__=_==_'+';__*=_;_=~-_'*_)
_=+__

Try it online!

Can compute 125! with ease.

Works using an 'exec' pseudo-loop:

  • First, we set __ to True, which is equivalent to 1.
  • We multiply this by _ (the input), and then decrement _.
  • The second step is repeated _ (input) times using string multiplication in the __ (exec) function's argument.
\$\endgroup\$
0
\$\begingroup\$

PHP, 40 39 bytes

<?=array_product(range($argv[1]?:1,1));

Thanks to @JoKing for saving 1 byte and correcting the input

Try it online!

\$\endgroup\$
  • \$\begingroup\$ @JoKing changed the answer to reflect 🤓 \$\endgroup\$ – EvanBarbour3 Feb 19 at 12:05
0
\$\begingroup\$

Kotlin, 50 45 bytes

fun f(x:Int):Int=when(x){0->1;else->x*f(x-1)}

Thanks to @jonathan-frech

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG. I think the 1->1; clause is superfluous. \$\endgroup\$ – Jonathan Frech Feb 19 at 14:22
0
\$\begingroup\$

><>, 14 bytes

1$:@?!n$:1-@*!

Try it online!

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

Excel Formula, 41 bytes

The following should be entered as an array formula (Ctrl+Shift+Enter):

=IFERROR(PRODUCT(ROW(OFFSET(A1,,,A1))),0)

Where A1 contains the value for n.

The IFERROR is just there to handle n=0.

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

Python 2, 52 bytes

I'm posting this purely because it uses reduce :)

f=lambda x:x<1or reduce(lambda a,b:a*b,range(1,x+1))

Try it online

Note: returns True for n<1. I assume this is ok because True == 1

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

NuStack, 55 bytes

f(n:int):int{r:int=n;while(n>1){n=n-1;r=r*n;}return r;}

Naive while-based approach

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

Swift - 53 Characters

func f(_ x:Double)->(Double){return(x<2 ?1:x*f(x-1))}

I'm sure it can be improved using closures...still investigating.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG. There is already a Swift answer in 43 bytes. (It doesn't mean you can't post. But you may want to have a look at the existing answers in the same language first.) \$\endgroup\$ – jimmy23013 May 29 at 0:10
  • \$\begingroup\$ Welcome to the site! Since you are golfing in Swift you might want to check out our tips for golfing in swift question. There is one of these for most other languages as well. \$\endgroup\$ – Sriotchilism O'Zaic May 29 at 2:29
  • \$\begingroup\$ Thanks for the prompt feedback - much appreciated! \$\endgroup\$ – L Rettberg May 30 at 18:07
0
\$\begingroup\$

Pepe, 60 bytes

rrEERREeeeeeeeErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE

Try it online!

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

Dreaderef, 47 bytes

"??"-14"?"-1"?"*-1" "-1" "

Try it online! Takes input from command-line arguments.

This file contains unprintables. A hexdump is provided below:

00000000: 2201 1604 043f 0703 3f22 2d31 3422 0b02  "....?..?"-14"..
00000010: 3f1c 222d 3122 0116 1303 013f 1202 222a  ?."-1".....?.."*
00000020: 2d31 2216 0120 222d 3122 0112 2005 22    -1".. "-1".. ."

Ungolfed, the program looks like this:

; Jump to 28 if N = 0
0.   deref 22 4
3.   bool  ?  7
6.   mul   ?  -14 11
10.  add   ?  28  -1

; R = R * N
14.  deref 22 19
17.  mul   1  ?   18

; N = N - 1
21.  add   *  -1  22

; Jump to start
25.  deref 32 -1

; Print R
28.  deref 18 32
31.  numo  ?

There are two variables: N, which is located at position 22 and initialized to the input integer, and R, which is located at position 18 and initialized to 1.

\$\endgroup\$

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.