# Find the Factorial!

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.

• 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)? – Ami Feb 6 '11 at 22:43
• @SHiNKiROU, even golfscript can manage 125! less than 1/10th of a second and it's and interpreted interpreted language! – gnibbler Feb 8 '11 at 3:21
• @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. – Michael Stern Jan 7 '14 at 3:18
• Completes in under a minute seems a very hardware-dependent requirement. Completes in under a minute on what hardware? – sergiol Aug 24 '17 at 18:05
• @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. – Kevin Brown Aug 24 '17 at 21:20

## Pyke, 2 bytes (non-competing)

SB


Try it here!

   - implicit input
S  -  range(1, input+1)
B - product(^)


# JavaScript ES6, 19 17 bytes

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


Saved two bytes by changing the conditional to n instead of n>1, because they are effectively equal.

## Ungolfed

var factorial = function(n) {
if (n > 1) {
return f(n-1)*n;
} else {
return 1;
}
}


Works just like a standard factorial. Defines a function f which multiplies it's input n by f(n-1). If n is equal to 0 or 1, then the function returns 1.

## See it in Action

Check it out on JSFiddle!

• Yes, exactly the same as my answer from 2 years previously. – MT0 Jun 8 '16 at 20:06

Mathcad byte-equivalence system yet to be determined. Some operators cannot be entered as text but have keyboard "shortcuts" instead (or can be picked from a toolbar). For example, the product operator is inserted using the key combination ctl-# ; this results in a capital Pi symbol being placed upon the Mathcad worksheet, together with 4 associated placeholders (black rectangles) which hold the iteration variable, starting value, final value and the expression for each element of the product. Balanced parentheses can be entered (in most cases) using the quote key. Typing : enters the assignment operator :=.

Mathcad has both a standard IEEE numerical floating point processing system and a longnum symbolic processing system that run in parallel over the same worksheet. = is the numeric evaluation operator whilst → is the symbolic evaluation operator.

# Java, 51 bytes

class a{double A(double b){return b<1?1:b*A(b-1);}}


I'm actually glad Coding Ground can handle more stack frames than what is needed to overflow a double with this.

• I'd +1 if the result was precise for n=125, but it is not (also, not that I reduced your byte count to 39). – Olivier Grégoire Dec 24 '17 at 11:09

## Neoscript, 31 bytes

{n|(0:(]:n):reduce({x y|x*y}1)}


## Logy, 47 bytes

f[X]->include["@stdlib.logy"]~product[..[2,X]];


Trivial. Return the product of the range [2..n]

# Bash w/Core Utils & BC, 15 Bytes

Saw 2 other bash solutions, but both longer than this one:

seq -s* dd|bc


number to factorial for from stdin, factorial to stdout

proc f n {expr $n?($n)*\[f $n-1]:1}  Try it online! # 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


# 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

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

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

# 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

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


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

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


# 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  # 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). # 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 • 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;} – mgthomas99 Sep 11 '18 at 21:45 • @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. – Olivier Grégoire Sep 12 '18 at 7:48 # 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  # 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. # 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!

• @JoKing changed the answer to reflect 🤓 – EvanBarbour3 Feb 19 '19 at 12:05

# Kotlin, 50 45 bytes

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


Thanks to @jonathan-frech

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

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

# 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

# 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

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

• 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.) – jimmy23013 May 29 '19 at 0:10
• 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. – Post Rock Garf Hunter May 29 '19 at 2:29
• Thanks for the prompt feedback - much appreciated! – L Rettberg May 30 '19 at 18:07

# Pepe, 60 bytes

rrEERREeeeeeeeErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE


Try it online!

# C, 37 bytes

long double f(n){return!n?1:n*f(n-1);}


This program accepts one number from stdin and then prints the answer in floating point form.

• Hello, and welcome to Code Golf! This is a great answer, but to reduce the byte count even more, why not remove the extra spaces? – NoOneIsHere Aug 3 '19 at 22:23
• Oh, so you only want the nonmain function. Alright. I will keep that in mind for next time. – T. Salim Aug 3 '19 at 22:33
• You are right Jo, I fixed it. – T. Salim Aug 4 '19 at 0:05
• Thank you A__, I removed the parentheses. – T. Salim Aug 4 '19 at 2:41
• No, I tried to simply use long but the computer outputted 0 due to overflow, so I kept it as long double. – T. Salim Aug 4 '19 at 2:45

# Pip, 13 bytes

Fi,a{o*:i+1}o


Try it online!

Recursive factorial is given in Pip documentation, so I did iterative. Also, it couldn't handle up to 125! anyway.

# Keg, 95 4 bytes

Ï⑨∑*


Try it online!

-1 byte thanks to @A̲̲

### 5 Bytes

Ï_1∑*


Try it online!

This:

• Takes the (Ï)ota of the implicit input (pushes input, input - 1, input - 2 ... 0)
• Pops the bottom 0
• Pushes an extra 1 (so that the 0 case works)
• Multiplies the entire stack together