title: Find the Factorial!

text:
# Question
Title: 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.

# Answer
## Golfscript -- 12 chars

```
{,1\{)*}/}:f

```

---

### Getting started with Golfscript -- Factorial in step by step

Here's something for the people who are trying to learn golfscript. The prerequisite is a basic understanding of golfscript, and the ability to read golfscript documentation.

So we want to try out our new tool golfscript. It's always good to start with something simple, so we're beginning with factorial. Here's an initial attempt, based on a simple imperative pseudocode:

```
# pseudocode: f(n){c=1;while(n>1){c*=n;n--};return c}
{:n;1:c;{n 1>}{n c*:c;n 1-:n;}while c}:f

```

Whitespace is very rarely used in golfscript. The easiest trick to get rid of whitespace is to use different variable names. Every token can be used as a variable (see the syntax page). Useful tokens to use as variables are special characters like `|`, `&`, `?` -- generally anything not used elsewhere in the code. These are always parsed as single character tokens. In contrast, variables like `n` will require a space to push a number to the stack after. Numbers are essentially preinitialized variables.

As always, there are going to be statements which we can change, without affecting the end result. In golfscript, everything evaluates to true except `0`, `[]`, `""`, and `{}` (see this). Here, we can change the loop exit condition to simply `{n}` (we loop an additional time, and terminate when n=0).

As with golfing any language, it helps to know the available functions. Luckily the list is very short for golfscript. We can change `1-` to `(` to save another character. At present the code looks like this: (we could be using `1` instead of `|` here if we wanted, which would drop the initialization.)

> `{:n;1:|;{n}{n|*:|;n(:n;}while|}:f`

It is important to use the stack well to get the shortest solutions (practice practice practice). Generally, if values are only used in a small segment of code, it may not be necessary to store them into variables. By removing the running product variable and simply using the stack, we can save quite a lot of characters.

> `{:n;1{n}{n*n(:n;}while}:f`

Here's something else to think about. We're removing the variable `n` from the stack at the end of the loop body, but then pushing it immediately after. In fact, before the loop begins we also remove it from the stack. We should instead leave it on the stack, and we can keep the loop condition blank.

> `{1\:n{}{n*n(:n}while}:f`

Maybe we can even eliminate the variable completely. To do this, we will need to keep the variable on the stack at all times. This means that we need two copies of the variable on the stack at the end of the condition check so we don't lose it after the check. Which means that we'll have a redundant `0` on the stack after the loop ends, but that is easy to fix.

This leads us to our optimal `while` loop solution!

> `{1\{.}{.@*\(}while;}:f`

Now we still want to make this shorter. The obvious target should be the word `while`. Looking at the documentation, there are two viable alternatives -- unfold and do. When you have a choice of different routes to take, try and weigh the benefits of both. Unfold is 'pretty much a while loop', so as an estimate we'll cut down the 5 character `while` by 4 into `/`. As for `do`, we cut `while` by 3 characters, and get to merge the two blocks, which might save another character or two.

There's actually a big drawback to using a `do` loop. Since the condition check is done after the body is executed once, the value of `0` will be wrong, so we may need an if statement. I'll tell you now that unfold is shorter (some solutions with `do` are provided at the end). Go ahead and try it, the code we already have requires minimal changes.

> `{1\{}{.@*\(}/;}:f`

Great! Our solution is now super-short and we're done here, right? Nope. This is 17 characters, and J has 12 characters. Never admit defeat!

---

### Now you're thinking with... recursion

Using recursion means we *must* use a branching structure. Unfortunate, but as factorial can be expressed so succinctly recursively, this seems like a viable alternative to iteration.

```
# pseudocode: f(n){return n==0?n*f(n-1):1}
{:n{n.(f*}1if}:f # taking advantage of the tokeniser

```

Well that was easy -- had we tried recursion earlier we may not have even looked at using a `while` loop! Still, we're only at 16 characters.

---

### Arrays

Arrays are generally created in two ways -- using the `[` and `]` characters, or with the `,` function. If executed with an integer at the top of the stack, `,` returns an array of that length with arr\[i\]=i.

For iterating over arrays, we have three options:

1. `{block}/`: push, block, push, block, ...
2. `{block}%`: \[ push, block, push, block, ... \] (this has some nuances, e.g. intermediate values are removed from the stack before each push)
3. `{block}*`: push, push, block, push, block, ...

The golfscript documentation has an example of using `{+}*` to sum the contents of an array. This suggests we can use `{*}*` to get the product of an array.

```
{,{*}*}:f

```

Unfortunately, it isn't quite that simple. All the elements are off by one (`[0 1 2]` instead of `[1 2 3]`). We can use `{)}%` to rectify this issue.

```
{,{)}%{*}*}:f

```

Well not quite. This doesn't handle zero correctly. We can calculate (n+1)!/(n+1) to rectify this, although this costs far too much.

```
{).,{)}%{*}*\/}:f

```

We can also try to handle n=0 in the same bucket as n=1. This is actual extremely short to do, try and work out the shortest you can.

> Not so good is sorting, at 7 characters: `[1\]$1=`. Note that this sorting technique does has useful purposes, such as imposing boundaries on a number (e.g. \`\[0\100\]$1=)
> Here's the winner, with only 3 characters: .!+

If we want to have the increment and multiplication in the same block, we should iterate over every element in the array. Since we aren't building an array, this means we should be using `{)*}/`, which brings us to the shortest golfscript implementation of factorial! At 12 characters long, this is tied with J!

> `{,1\{)*}/}:f`

---

### Bonus solutions

Starting with a straightforward `if` solution for a `do` loop:

```
{.{1\{.@*\(.}do;}{)}if}:f

```

We can squeeze a couple extra out of this. A little complicated, so you'll have to convince yourself these ones work. Make sure you understand all of these.

```
{1\.!!{{.@*\(.}do}*+}:f
{.!{1\{.@*\(.}do}or+}:f
{.{1\{.@*\(.}do}1if+}:f

```

A better alternative is to calculate (n+1)!/(n+1), which eliminates the need for an `if` structure.

> `{).1\{.@*\(.}do;\/}:f`

But the shortest `do` solution here takes a few characters to map 0 to 1, and everything else to itself -- so we don't need any branching. This sort of optimization is extremely easy to miss.

> `{.!+1\{.@*\(.}do;}:f`

For anyone interested, a few alternative recursive solutions with the same length as above are provided here:

```
{.!{.)f*0}or+}:f
{.{.)f*0}1if+}:f
{.{.(f*}{)}if}:f

```

---

\*note: I haven't actually tested many of the pieces of code in this post, so feel free to inform if there are errors.
> 73 votes

# Answer
# Python - 27

Just simply:

```
f=lambda x:0**x or x*f(x-1)

```
> 58 votes

# Answer
## Haskell, 17

```
f n=product[1..n]

```
> 50 votes

# Answer
## APL (4)

```
×/∘⍳

```

Works as an anonymous function:

```
    ×/∘⍳ 5
120

```

If you want to give it a name, 6 characters:

```
f←×/∘⍳

```
> 32 votes

# Answer
# Mornington Crescent, 1827 1698 chars

I felt like learning a new language today, and this is what I landed on... (Why do I do this to myself?) This entry won't be winning any prizes, but it beats all 0 other answers so far using the same language!

```
Take Northern Line to Bank
Take Central Line to Holborn
Take Piccadilly Line to Heathrow Terminals 1, 2, 3
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Parsons Green
Take District Line to Bank
Take District Line to Parsons Green
Take District Line to Acton Town
Take District Line to Hammersmith
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Hammersmith
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Parsons Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Temple
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Bank
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Embankment
Take Circle Line to Embankment
Take Northern Line to Angel
Take Northern Line to Moorgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Moorgate
Take Circle Line to Moorgate
Take Northern Line to Mornington Crescent

```

Try it online!

Anyone who's journeyed around London will understand that instantly of course, so I'm sure I don't need to give a full explanation.

Most of the work at the start is in handling the 0 case. After initialising the product at 1, I can use that to calculate max(input, 1) to get the new input, taking advantage of the fact that 0! = 1! Then the main loop can begin.

(EDIT: A whole bunch of trips have been saved by stripping the 1 from "Heathrow Terminals 1, 2, 3" instead of generating it by dividing 7 (Sisters) by itself. I also use a cheaper method to generate the -1 in the next step.)

Decrementing is expensive in Mornington Crescent (although less expensive than the Tube itself). To make things more efficient I generate a -1 by taking the NOT of a parsed 0 and store that in Hammersmith for much of the loop.

---

I put some significant work into this, but since this is my first attempt at golfing in Mornington Crescent (in fact my first attempt in *any* language), I expect I missed a few optimisations here and there. If you're interested in programming in this language yourself (and why wouldn't you be?), Esoteric IDE \- with its debug mode and watch window - is a must!
> 22 votes

# Answer
# , 12 bytes

A standard definition in J:

```
f=:*/@:>:@i.

```

Try it online!

Less than 1sec for 125!

Eg:

```
 f 0
 1
 f 5
 120
  f 125x
 1882677176888926099743767702491600857595403
 6487149242588759823150835315633161359886688
 2932889495923133646405445930057740630161919
 3413805978188834575585470555243263755650071
 31770880000000000000000000000000000000

```
> 19 votes

# Answer
## Golfscript - 13 chars **(SYM)**

defines the function `!`

```
{),()\{*}/}:!             # happy robot version \{*}/

```

alternate 13 char version

```
{),()+{*}*}:!

```

whole program version is **10 chars**

```
~),()+{*}*

```

testcases take less than 1/10 second:

**input:**

```
0!

```

**output**

```
1

```

**input**

```
125!

```

**output**

```
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```
> 18 votes

# Answer
# MATL, 2 bytes

```
:p

```

Explained:

```
:    % generate list 1,2,3,...,i, where i is an implicit input
p    % calculate the product of of all the list entries (works on an empty list too)

```

Try it online!
> 17 votes

# Answer
## Perl 6: 13 chars

```
$f={[*]1..$_}

```

`[*]` is same as Haskell `product`, and `1..$_` is a count-up from 1 to `$_`, the argument.
> 13 votes

# Answer
# Python 2, 28 bytes

```
f=lambda x:x/~x+1or x*f(x-1)

```

Try it online!

(based off Alexandru's solution)
> 11 votes

# Answer
# Java (JDK), 85 bytes

```
BigInteger f(int n){return n<2?BigInteger.ONE:new BigInteger(""+n).multiply(f(n-1));}

```

Try it online!
> 10 votes

# Answer
# F# (.NET Core), 26 bytes

There's no inbuilt product function in F#, but you can make one with a fold

```
let f n=Seq.fold(*)1{1..n}

```

Try it online!
> 9 votes

# Answer
# Matlab, 15

```
f=@(x)prod(1:x)

```

Test Cases

```
>> f(0)
ans =
     1
>> f(4)
ans =
    24
>> tic,f(125),toc
ans =
  1.8827e+209
Elapsed time is 0.000380 seconds.

```
> 9 votes

# Answer
# Ruby, 21 bytes

```
f=->n{n>1?n*f[n-1]:1}

```

Try it online!

## Test

```
irb(main):009:0> f=->n{n>1?n*f[n-1]:1}
=> #<Proc:0x25a6d48@(irb):9 (lambda)>
irb(main):010:0> f[125]
=> 18826771768889260997437677024916008575954036487149242588759823150835315633161
35988668829328894959231336464054459300577406301619193413805978188834575585470555
24326375565007131770880000000000000000000000000000000

```
> 8 votes

# Answer
## JavaScript, 25

```
function f(n)!n||n*f(n-1)

```

## CoffeeScript, 19

```
f=(n)->!n||n*f(n-1)

```

Returns `true` in the case of n=0, but JavaScript will type-coerce that to 1 anyway.
> 8 votes

# Answer
# PostScript, 26 chars

```
/f{1 exch -1 1{mul}for}def

```

Example:

```
GS> 0 f =
1
GS> 1 f =
1
GS> 8 f =
40320

```

The function itself takes only 21 characters; the rest is to bind it to a variable. To save a byte, one can also bind it to a digit, like so:

```
GS> 0{1 exch -1 1{mul}for}def
GS> 8 0 load exec =
40320

```
> 7 votes

# Answer
# Brachylog, ~~7~~ 6 bytes

By making a range and multiplying it

-1 byte tanks to ovs having the idea to use the max() function

```
;1⌉⟦₁×

```

## Explanation

```
;1          --  If n<1, use n=1 instead (zero case)
  ⟦₁        --      Construct the range [1,n]
    ×       --      return the product of said range

```

Try it online!

---

# Brachylog, ~~10~~ 9 bytes

recursion

```
≤1|-₁↰;?×

```

## Explanation

```
            --f(n):
≤1          --  if n ≤ 1: return 1
|           --  else:
 -₁↰        --      f(n-1)
    ;?×     --            *n

```

Try it online!
> 7 votes

# Answer
# Ruby - ~~30~~ 29 characters

```
def f(n)(1..n).inject 1,:*end

```

Test

```
f(0) -> 1
f(5) -> 120

```
> 6 votes

# Answer
# C#, 20 or 39 characters depending on your point of view

As a traditional instance method (39 characters; tested here):

```
double f(int x){return 2>x?1:x*f(x-1);}

```

As a lambda expression (20 characters, but see disclaimer; tested here):

```
f=x=>2>x?1:x*f(x-1);

```

We have to use `double` because 125! == 1.88 * 10209, which is much higher than `ulong.MaxValue`.

### Disclaimer about the lambda version's character count:

If you recursion in a C# lambda, you obviously have to store the lambda in a named variable so that it can call itself. But unlike (e.g.) JavaScript, a self-referencing lambda must have been declared **and initialized** on a previous line. You can't call the function in the same statement in which you declare and/or initialize the variable.

In other words, this doesn't work:

```
Func<int,double> f=x=>2>x?1:x*f(x-1); //Error: Use of unassigned local variable 'f'

```

But this does:

```
Func<int,double> f=null;
f=x=>2>x?1:x*f(x-1);

```

There's no good reason for this restriction, since `f` can't ever be unassigned at the time it runs. The necessity of the `Func<int,double> f=null;` line is a quirk of C#. Whether that makes it fair to ignore it in the character count is up to the reader.

# CoffeeScript, 21 19 characters for real

```
f=(x)->+!x||x*f x-1

```

**Tested here:** http://jsfiddle.net/0xjdm971/
> 6 votes

# Answer
# Javascript, ES6 17

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

```

ES6:

* Arrow function
> 6 votes

# Answer
# Aheui (esotope), ~~93~~ ~~90~~ 87 bytes

```
박밴내색뱅뿌뮹
숙쌕빼서빼처소
타뿌싼때산쑥희
매차뽀요＠어몽

```

Try it online!

Nice, small, and fast code. Slightly golfed after writing explanation. I'll not change it, because it is just same code.

# Explaination

Aheui is befunge-like language and (almost) every character of Aheui is operator. Part of character looks like `ㅏ, ㅐ, ㅓ, ㅜ, ㅛ, ㅗ, ㅢ` determines direction where next operator execute.  is left-to-right,  is right-to-left,  is down-to-up,  is up-to-down,  is down-to-up, with skipping one character in two characters.  is 'nothing' : keep same speed and direction.

```
박밴내

```

commend is store given number in current stack,  commend is divide upmost two number in current stack. Both  and  store 2, so `박밴내` store 1 in current stack(default  or `nothing` stack)

```
색뱅

```

commend change current stack.  change stack to  (or ) stack.  commend with  (like  or ) get a number from STDIN. So `색뱅` get a number and store it in stack `악(ㄱ)`.

```
뿌
처

```

commend duplicate upmost value in current stack, and  commend pop value from current stack and see if it is 0. If it is, it go to opposite direction from  indicate : in here right-to-left. If it is not, it go to direction where  indicate. So `뿌(\n)처` see if input is 0 or not, and go right if zero, and go left if not.

```
망희
소

```

If input is zero, here is evaluated. (from  commend) First, change current stack to `nothing`().  commend is pop, and if used with  it print value as number.  halts program. So it print 1 and halt.

```
숙쌕빼서빼
타뿌싼때산쌕꾸
매차뽀요애애어

```

Look at this image for help. Here is main loop.  is subtraction, and  is multiply.  move value from current stack to selected one.

Put it shortly, it get number from `nothing` stack(or get 1), subtract to find if it is zero, and if not zero multiply and restart loop. And if zero, go to rightmost place of code with popping one number.

Print number, then pointer go to  : halt.

In one image :

SEL is select, MOV is move, DUP is duplicate. This image is produced by AheuiChem, Aheui development tool in Korean. Translated with paint tool of windows.
> 6 votes

# Answer
# 8088 / 8087 machine code, 13 bytes

```
D9 E8       FLD1                ; start with 1
E3 08       JCXZ DONE           ; if N = 0, return 1
        FACT_LOOP:
51          PUSH CX             ; push current N onto stack
8B F4       MOV  SI, SP         ; SI to top of stack for N
DE 0C       FIMUL WORD PTR[SI]  ; ST = ST * N
59          POP  CX             ; remove N from stack
E2 F8       LOOP FACT_LOOP      ; decrement N, loop until N = 0
        DONE:
C3          RET                 ; return to caller

```

Input **\\$n\\$** is in `CX`, output **\\${n!}\\$** is in `ST(0)`.

Test output displayed using Borland Turbo Debugger 3:

**n = 1:**

**n = 15:**

**n = 50:**

**n = 125:**

**Notes:**

* Calculates \\${125!}\\$ in an imperceptible amount of time (difficult to accurately profile in DOS)
* Language is not newer than the challenge
> 6 votes

# Answer
# C (39 chars)

```
double f(int n){return n<2?1:n*f(n-1);}

```
> 5 votes

# Answer
# Jelly, 2 bytes

```
RP

```

Try it online!

Alternatively, a builtin answer is one byte:

```
!

```

Try it online!
> 5 votes

# Answer
# Pari/GP, 45 bytes

```
x=input();forstep(y=x-1,1,-1,x=x*y);print(x);

```

Try it online!
> 5 votes

# Answer
## PowerShell, 42 bytes

(saved 2 chars using *filter* instead of *function*)

```
filter f($x){if(!$x){1}else{$x*(f($x-1))}}

```

Output:

```
PS C:\> f 0
1
PS C:\> f 5
120
PS C:\> f 1
1
PS C:\> f 125
1.88267717688893E+209

```
> 4 votes

# Answer
# D: 45 Characters

```
T f(T)(T n){return n < 2 ? 1 : n * f(n - 1);}

```

More legibly:

```
T f(T)(T n)
{
    return n < 2 ? 1 : n * f(n - 1);
}

```

A cooler (though longer version) is the templatized one which does it all at compile time (**64 characters**):

```
template F(int n){static if(n<2)enum F=1;else enum F=n*F!(n-1);}

```

More legibly:

```
template F(int n)
{
    static if(n < 2)
        enum F = 1;
    else
        enum F = n * F!(n - 1);
}

```

Eponymous templates are pretty verbose though, so you can't really use them in code golf very well. D's already verbose enough in terms of character count to be rather poor for code golf (though it actually does *really* well at reducing overall program size for larger programs). It's my favorite language though, so I figure that I might as well try and see how well I can get it to do at code golf, even if the likes of GolfScript are bound to cream it.
> 4 votes

# Answer
## PowerShell – 36

Naïve:

```
filter f{if($_){$_*(--$_|f}else{1}}

```

Test:

```
> 0,5,125|f
1
120
1,88267717688893E+209

```
> 4 votes

# Answer
## Scala, 39 characters

```
def f(x:BigInt)=(BigInt(1)to x).product

```

Most of the characters are ensuring that `BigInt`s are used so the requirement for values up to 125 is met.
> 4 votes

# Answer
# 05AB1E, 4 bytes

Code:

```
L0KP

```

Explanation:

```
L     # Create the list [1, ..., input]
 0K   # Remove all occurencies of zero
   P  # Calculate the product

```

I have no idea why this works for **0**, but it does.
> 4 votes

# Answer
# Racket (scheme) 40 35 29 bytes

Computes 0! to be 1, and computes 125! in 0 seconds according to timer. Regular recursive approach

```
(define(f n)(if(= n 0)1(* n(f(- n 1)))))

```

New version to beat common lisp: multiplies all elements of a list (same as that Haskell solution)

```
(λ(n)(apply *(build-list n add1)))

```

Newer version to beat the other scheme solution and math the other racket solution by using foldl instead of apply and using range instead of buildlist

```
(λ(n)(foldl * n(range 1 n)))

```
> 4 votes

# Answer
# Python, 25 bytes

```
f=lambda x:x<2or x*f(x-1)

```

**Try it online!**

This is a recursive lambda. It returns `True` if the factorial is `1` (inputs 1 and 0), but that's allowed by meta.
> 4 votes

# Answer
# Python 2, 45 bytes

```
lambda n:reduce(long.__mul__,range(1,n+1),1L)

```

Try it online! Not the shortest Python solution but I thought it would be interesting to post a solution with `reduce` and `long.__mul__`.
> 4 votes

# Answer
# Flurry, 32 bytes

```
{{}{<{}(<><<>()>{})>}[(<>())()]}

```

This is an anonymous function that takes an argument as a Church numeral and returns a Church numeral as output.

You can test it with the interpreter as follows:

```
$ ./Flurry -nin -c '{{}{<{}(<><<>()>{})>}[(<>())()]}{}' 9
362880

```

While the function itself returns quickly for N=125, the resulting Church numeral is too large to be practically useful for any purpose, including being converted into an integer and displayed by the interpreter.

## Explanation

As with my Fibonacci answer, we're iterating a function \\$n\\$ times and storing an additional variable using the stack. In this case, the variable on the stack is the counter, so the step function looks like this:

```
next = λn. n * push(1 + pop())

```

This admits a straightforward translation that uses function composition for multiplication and `<><<>()>` for the successor function:

```
{<{} (<> <<> ()> {})>}

```

The main function is responsible for setting up initial values and calling `next` the appropriate number of times. It looks like this:

```
main = λn. push(0); n (next) (1)

```

The Church numeral representation of zero is `λab. b`; in other words, a constant function that ignores its argument and returns the identity function. By coincidence, the Church numeral representation of one is `λab. ab`, which is itself the identity function. Thus we can rewrite it as:

```
main = λn. n (next) (push(0) (arbitrary value))

```

This can again be translated directly:

```
{{} {<{}(<><<>()>{})>} [(<>()) ()]}

```
> 4 votes

# Answer
# V (vim), 33 bytes

```
S<C-r>=r<Tab>1,<C-r>"<BS>)
<C-o>:%s/\n/*/g
<C-o>C<C-r>=<C-r>"<BS><BS>

```

Try it online!

Explanation:

```
S<C-r>=r<Tab>1,<C-r>"<BS>)  # Replace N with [1, ..., N]
<C-o>:%s/\n/*/g             # Merge all lines with *
<C-o>C<C-r>=<C-r>"<BS><BS>  # Remove trailing * and evaluate.

```

Overflows for any `N` greater than `49`, but would work properly otherwise.
> 4 votes

# Answer
## Befunge - 2x20 = 40 characters

```
0\:#v_# 1#<\$v *\<
    >:1-:#^_$>\:#^_$

```

This is a function in that it is a standalone block of code not utilising the wraparound. You have to place the argument on the top of the stack then enter from the top-left going right, the function will exit from the bottom-right going right with the result on the top of the stack.

E.g. to calculate the factorial of 125

```
555**   0\:#v_# 1#<\$v *\<
            >:1-:#^_$>\:#^_$    .@

```

Testing 0

```
0   0\:#v_# 1#<\$v *\<
        >:1-:#^_$>\:#^_$    .@

```
> 3 votes

# Answer
# Python, 35 bytes

```
def f(n):return n and n*f(n-1) or 1

```

or

```
def f(n):return n*f(n-1) if n else 1

```
> 3 votes

# Answer
# J - 6 characters

```
*/>:i.

```

Does this count? I know it is very similar to the earlier J example, but it is a little shorter :)

I'm a beginner with J, but it's a lot of fun so far!
> 3 votes

# Answer
# In C (23 Characters)

This abuses the GCC "feature" that makes the last assignment count as a return if no return is specified.

```
f(a){a=a>0?f(a-1)*a:1;}

```

In proper C, 28 characters

```
f(a){return a>0?f(a-1)*a:1;}

```
> 3 votes

# Answer
## Kona (~~11~~ 6)

```
*/1.+!

```

K works right-to-left (for the most part), so we enumerate `x` (make a list/array of numbers from `0` to `x-1`), add `1` to it (list ranges `0` to `x`), then multiply all numbers together. If it weren't a requirement to compute `125!`, I could save 1 more byte by eliminating `.` next to the `1`. In any event, 125! is computed in mere milliseconds:

```
  */1.+!125.
1.882677e+209

```
> 3 votes

# Answer
# Julia - 14 characters (19 with non-arbitrary-precision input)

```
f(n)=prod(1:n)

```

If you want it to work all the way up to n=125, precision becomes an issue. If requiring the input value to be "big" to match the output is unacceptable, then an extra 5 characters can be used to overcome the problem:

```
g(n)=prod(1:big(n))

```

`big(n)` converts n to an arbitrary precision integer, and the code remains in arbitrary precision from there. The alternative is, with the 14 character code above, making the input arbitrary precision - for instance, calling `f(big(125))`.

**Edit**: Note that the above was from 2014, and was for Julia 0.2. There are some tricks to squeeze the code down in modern Julia - for example, in Julia 1.8.5, `!n=prod(1:n)` is 12 characters, and can be used as `!125`, for example. Original answer kept as the "real" one for posterity.
> 3 votes

# Answer
# Haskell, 20

Gee, I sure hope folds don't count as built in functions...

```
f n=foldl(*)1[1..n]

```
> 3 votes

# Answer
# BrainFuck, 125 / CompressedFuck, 47

```
,[>+>+>>>+<<<<<-]>>-<[[>[->+>+<<]>>[-<<+>>]<<<-]>>>>[<<<<+>>>>-]<<<<->[-]>[<+>-]<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<<<-]>.

```

In 8-bit text encodings the program had 1000 bits.

However, any BrainFuck program could be stored with a 3-bit encoding. 125\*3=375

375 bits / 8 = 47 bytes

EDIT: In the CompressedFuck format it has 47 bytes :)

Also I forgot to mention that this program only works with infinite-sized cells
> 3 votes

# Answer
## Pyth, 8 bytes

It's a shame that, 5 years after the challenge has been posted, there is no pyth answer. So I'm doing it now, even if it's ridiculous :). BTW, this is non-competiting, since the language is newer than the challenge...

`Lu*GHSb1`

You call it with `yx`, where `x` is a number. Test it here !

## Explanation

```
Lu*GHSb1
L          Defines a lambda 'y' with argument 'b'
     Sb    Create a range from one to 'b' (function argument)
  *GH      Lambda function that takes two arguments and multiply them
 u     1   Reduce the range with the above lambda.

```
> 3 votes

# Answer
# Factor, 24 bytes

```
[ [1,b] 1 [ * ] reduce ]

```

Try it online!

Computes 125 factorial very quickly

-2 bytes thanks to @chunes

# Factor, 12 bytes

```
[ [1,b] Π ]

```

Try it online!

Thanks to @chunes
> 3 votes

# Answer
## Python, 29 bytes

```
f=lambda x:x and x*f(x-1)or 1

```
> 2 votes

# Answer
## JavaScript, 52 bytes

```
function f(m){n=1;for(i=1;i<=m;i++){n*=i;}return n;}

```
> 2 votes

# Answer
# Sage, 19 bytes

For some reason, Guido hates prod(). But, Sage supports it:

```
f=lambda n:prod(1..n)

```

edit: just had a statement previously, not a function
> 2 votes

# Answer
## PowerShell, 34

```
{($p=1)..$_-ge1|%{$p*=$_};$p}

```

Creates a list of numbers from one to the argument, selects those greater than or equal to one and multiplies those. For `0` the list `1, 0` will be created where then only 1 remains, yielding the correct answer.

To test:

```
> &{($p=1).."$args"-ge1|%{$p*=$_};$p} 125
1,88267717688893E+209

```

It's just a scriptblock; i.e. a function without a name.
> 2 votes

# Answer
## Pico, 23

```
f(x):if(x=0,1,x*f(x-1))

```

but Pico max out at 12:

```
>f(12)
479001600

```
> 2 votes

# Answer
# Golfscript, 10 chars:

```
~,{)}%{*}*

```
> 2 votes

# Answer
## Ruby, 19

`[1,*2..n].inject :*`

The extra hardcoded 1 at the beginning makes it work for when n=0.
Ruby auto-converts to BigInt after a certain point, so it has 100% accuracy.
> 2 votes

# Answer
## Mathematica

```
f = If[# > 0, # f[# - 1], 1] &
f[125] = 188267.....

```
> 2 votes

# Answer
# Mathematica, 17

```
f = Times@@Range@#&

```

works more or less instantaneously for `f[125]`.
> 2 votes

# Answer
# Ruby, 35 characters,

`def f(x);p 1.upto(x).inject(:*);end`

Test:

`f(5)`

`=> 120`
> 2 votes

# Answer
# Mathematica – 46 characters

```
f[x_]:=Integrate[(x+1)^(t-1)Exp[-x-1],{t,0,∞}]

```

This is using the integral definition of the **Gamma Function**.
> 2 votes

# Answer
# Bash, 14

```
seq -s\* $1|bc

```
* 7 bytes saved thanks to @JuanIgnacioDíaz

Try it online!
> 2 votes

# Answer
# Scheme - 33 characters

Improved answer using an unnamed procedure and the λ symbol.

```
(λ(n)(if(= 0 n)1(* n(!(- n 1)))))

```

Old 40 character answer below

```
(define(! n)(if(= 0 n)1(* n(!(- n 1)))))

```

The white-space requirement is almost as much of a problem as the brackets for bloating things in scheme.

Testing:

```
> ((λ(n) (if(= 0 n)1(* n(!(- n 1))))) 0)
1
> ((λ(n) (if(= 0 n)1(* n(!(- n 1))))) 125)
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```
> 2 votes

# Answer
# R, 22 (9 w/o function def; 35 w/ recursion)

Simply

```
f=function(n)prod(1:n)

```

Or, without defining a function:

```
prod(1:n)

```

Or, recursive:

```
f=function(n)if(n<2)1 else n*f(n-1)

```
> 2 votes

# Answer
## CJAM 9

I'm pretty sure this mmets all requirements. It ran on the online compiler for 125 is far less than a second.

```
1ri,{)*}%

```

It works as follows:

```
1         puts 1 on stack
ri        accepts input as integer
,         creates list of all non negative integers less than input
{         start block
          increments integer by 1
          multiplies current product by integer, current product starts with 1
}         repeat block for each element in list

```
> 2 votes

# Answer
# Ruby, 22 bytes

```
n.downto(1).inject(:*)

```
> 2 votes

# Answer
# Python, 30 bytes

```
f=lambda n:n*f(n-1)if n else 1

```

Saves some characters by using `lambda` syntax and a ternary if-else.
> 2 votes

# Answer
# Swift: 43

```
var f:Double->Double;f={$0<1 ?0:f($0-1)*$0}

```

Swift is definitely not made for conciseness, but I though let's give it a try anyways. This solution is obviously recursive.

There's also the more native Swift way to do it which is a bit longer (**57** characters):

```
let f={stride(from:1,through:$0,by:1.0).reduce(1){$0*$1}}

```

If it would be allowed to add an additional rule for very typey languages:

* You may add functions with the same behaviour as functions in the standard library for the purpose of shorter names

Then I would declare these two:

```
func ...(lhs: Double, rhs: Double) -> StrideThrough<Double> {
    return stride(from: lhs, through: rhs, by: 1)
}

extension SequenceType {
    func r<T>(initial: T, @noescape _ combine: (T, Self.Generator.Element) -> T) -> T {
        return reduce(initial, combine: combine)
    }
}

```

which redeclares `stride(from: a, through: b, to:1.0)` to `a...b` which I even think should be in the standard library, and `reduce(a, combine: f)` becomes `r(a, f)`. This would one enable to do this:

```
let f={(1...$0).r(1,*)}

```

which would be **23** characters.

I'm even thinking about creating a Code Golf Swift extension, which just redeclares all the standard methods to something more concise.

Any of those can be called like:

```
f(0) // 0
f(120) // 6.689502913449124e+198
f(170) // 7.257415615307994e+306

```

All of them can go up to 170, where the result will be `Double.infinity` when above.

The times are as follows (for input `170`):

```
recursive (43 chars): 0.00000101 s
native (rule-bend)  : 0.00000027 s
native              : 0.00000027 s

```
> 2 votes

# Answer
**JavaScript ES6 21 chars**

> Note: I'm just extending Casey Chu's answer using ES6 with minor change

```
f=(n)=>n<2?1:n*f(n-1)

```

fiddle: Factorial

1) Does not use any built-in functions

2) Calculates factorial up to 170

3) Calculates factorial for 0 too

4) Execution time is less than a millisecond

Note: It will work only in browsers that supports ES6. FF(22+) and Chrome(45+) supports arrow functions as per MDN at the time of writing this answer.
> 2 votes

# Answer
# Simplex v.0.5, 12 bytes

(The Docs page may be outdated; mainly, the `*` also increments the pointer and the `J` being the max of two elements.)

```
h*M{*LTRpM}]

```

This defines a macro that performs the factorial function on the current byte. It maintains the structure of the strip, but inserts an extra `0` at the next byte. You can delete this by adding another command `p` before the function ends.

This one works for inputs on a strip whose sole member is the input. I.e., a strip which looks like `[N,/,/,...]` (`/` is the empty or null bit.) It clocks in at…

# 11 Bytes!!

This beats the GolfScript entry, FYI.

```
h{*M}pwT1J]

```

This is what it does:

```
h{*M}pwT1J]
h         ] ~~ define new macro
 {  }       ~~ repeat inside until zero met
  *         ~~ copy the current byte and increment pointer
   M        ~~ decrement byte
     p      ~~ remove trailing zero
      wT    ~~ spreads T (multiplication) across strip backwards; sets pointer to after the result
        1J  ~~ Takes the maximum of 1 and the current byte

```

---

Here the non-destructive version being used in an example code:

```
h*M{*LTRpM}p]ih0o

```

This defines the macro, asks for numeric input (`i`), calls the first macro (`h0`) and outputs the byte as a number (`o`).

Here is the pseudo-code I used:

```
Function factorial(N)
    A = N - 1
    While A > 1
        N = A * N
        A = A - 1
    End While
    Return N
End Function

```

This is the expanded explanation.

```
h    ~~ open macro, implicit [
 *   ~~ A=N [N,A]
 M   ~~ A=N-1 [N,A-1]
 {   ~~ Loop until current byte is zero
  *  ~~ [N,A-1,A-1]
  LT ~~ [N*(A-1),0,A-1]
  Rp ~~ [N*(A-1),A-1]
  M  ~~ [N*(A-1),A-2]
 }
 p   ~~ [N!]
]    ~~ close macro

```
> 2 votes

# Answer
## Burlesque, 4 bytes

Burlesque has a built-in `?!` to do that, but since that is forbidden by the rules we can just use `ropd` (runs in less than a fraction of a second):

```
blsq ) 125ropd
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000
blsq ) 5ropd
120
blsq ) 125?!
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```

Basically factorial is just the product of a list `[1..N]` and `ro` creates `[1..N]` and `pd` is the product of a list. Simple as that.
> 2 votes

# Answer
# JacobFck, noncompeting

43 bytes. *This answer is noncompeting, because the language was invented after the challenge was posted.*

Might be a *bit* late but this is too good to pass up.

```
<^0|=_s~$t$c:m^1^c|=_e-$c^t*$t_m:e^t>!:s^1>

```

Here is the commented and expanded: here
> 2 votes

# Answer
# Detour (non-competing), 5 bytes

```
?1RP.

```

Try it online!

`?1` means "if n is 0, set n to 1"
`RP` means product \[1..n\], `.` is output

Terminates in **6ms** for 170 (the highest number whose factorial can be represented in JS) on my ~~craptop~~ 4-year-old macbook air with 2GB RAM.

Here's a 100% symbolic method:

# Detour, 10 bytes

```
[{<]?1}&*.

```

Try it online!

Old recursive way:

# Detour, ~~17~~ ~~13~~ 11 bytes

```
<Q0\
.$;p>P

```

Try it online!

This is non-competing, as I just finished the language today.

There's no good way to explain it, the website will give a visualization of the data flow at runtime.

It's a shame I have to handle 0!=1, or this could be a one-liner.

Another 11-byte solution (faster):

---

# Detour, 11 bytes

```
?1[$Q<]x
P.

```

Try it online!
> 2 votes

# Answer
## Python - 33

```
f=lambda n:n*(n and f(n-1))+(n<1)

```
> 2 votes

# Answer
## K, 9 bytes

```
f:*/1f+!:

k) f 125
1.882677e+209

```

Computes 125! in under a millisecond; 15ms for 10k iterations
> 2 votes

# Answer
# Common Lisp, 38 bytes

**Disclaimer: I'm not responsible for any traumatic effect caused by the extreme density of parentheses. It's the language specification's fault.**

```
(defun a(b)(if(< b 2)1(*(a(- b 1))b)))

```

Ungolfed & explained:

```
(defun a (b)                               ;Define a function called "a". It has one parameter called "b"
            (if (< b 2)                    ;If b is a number that is smaller than 2 (0 and 1 satisfy this)
                       1                   ;Return 1
                        (* (a (- b 1)) b)));Otherwise, return a(b-1) multiplied by b

```
> 2 votes

# Answer
# \>\<\>, ~~17~~ 16 bytes

```
1v;n
$<*}-1.!?::

```

-1 byte thanks to Jo King.

Since the question asks for a function as opposed to a full program, I allowed myself to accept the input from the stack without counting an additional 3 bytes for using the `-v` option.

This manages to be shorter than the other \>\<\> answer because it jumps to the end-of-iteration code without having to hardcode the jump destination address : the current iteration counter (duplicated) is used as an address.
The iteration stops when the counter is 0, and jumping to `(0, 0)` while the direction pointer points to the right will execute the `n;` code that is otherwise unreachable, displaying the result and stopping the execution.

It handles `0!` correctly and executes in 10\*(n+1) ticks for n \> 0 or 9 ticks for n = 0.

You can try it online.
> 2 votes

# Answer
# PHP, 39 bytes

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

```

**breakdown**

```
<?=                          // 4. print result
    array_product(           // 2. get product of the elements - special: 0
        range(1,$argv[1])    // 1. build array from 1 to N - special: [1,0]
    )
    ?:1                      // 3. special: if falsy, return 1
;

```
> 2 votes

# Answer
# Brain-Flak, 52 bytes

Came up with the solution independently, thanks JoKing for telling me that it's possible to get 52 bytes.

```
<>(())<>{(({})<({<>({})<><({}[()])>}{})<>{}>[()])}<>

```

Try it online!

---

Ungolfed:

```
<>(())<>		# push 1 on the other stack
{			# while x:
 (
  ({})			# copy x to the 3rd stack
  <(			# push the
   {			# running total of
    <>({})<>		# top of the other stack
    <({}[()])>		# (while decrementing x)
   }
   {}			# pop redundant 0
  )<>{}>
  [()]
 )			# push x-1
}
<>

```

Try it online!
> 2 votes

# Answer
# Flobnar, 19 bytes

```
|\@<:
1&::
<>-*
  1

```

Try it online!

An interesting sibling to Befunge. This uses the `-d` flag to enable decimal input.

### Explanation:

This is basically equivalent to the recursive function:

```
def f(x):
  if x == 0:
    return 1
  else:
    return x*f(x-1)

```

The program starts from the `@`, and evaluates to its left. The `\` evaluates underneath itself and stores that in the call stack. Underneath it is the `&`, which gives decimal input. If EOF has been reached, it evaluates underneath itself. Underneath, the `>` pushes the pointer right and returns the top value of the call stack minus 1.

That's this section:

```
 \@
 &:
 >-
  1

```

The `\` basically counts down from the input and stores the latest version in the call stack.

After that, it hits the `|`, which evaluates further along, and returns either the value above it if the evaluated value is non-zero, else the value below it. The `:` returns the top of the call stack, so if it is zero, the `|` goes down and returns 1, else it goes up and wraps around the field. It hits the `<` which wraps it around again, and then multiplies the top of the call stack by the next iteration of the function.

```
|  <:
1  :
<  *

```
> 2 votes

# Answer
# Julia 1.0, 12 bytes

```
n->prod(1:n)

```

Try it online!
> 2 votes

# Answer
## Keg, 16 bytes

```
(:|:1-)_(!1-|*).

```

This takes a top-of-stack item and returns \[0..top\]. Then, it discards the 0. After that, it multiplies everything in the stack, returning the factorial. (This is indeed too long.)
> 2 votes

# Answer
# Python 3, 30 Bytes

`f=lambda n:n*f(n-1)if n else 1`

125! took less than 1 second to do on IDLE and TIO.

How it works: the function `f` returns `n*f(n-1)` if `n` is not 0 and it returns 1 otherwise, the definition of a factorial.

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 17 bytes

Recursion. Usage of arrow function declaration and OR operator that checks whether x is 0 (if not, continue multiplying).

```
f=x=>!x||x*f(x-1)

```

Try it online!
> 2 votes

# Answer
# Hexagony, 25 bytes

```
?{)"(&=}<!{\.@*$><>}=/\._

```

Formatted:

```
   ? { ) "
  ( & = } <
 ! { \ . @ *
$ > < > } = /
 \ . _ . . .
  . . . . .
   . . . .

```

Try it online! or Try it online differently!
> 2 votes

# Answer
# Ruby - 20 chars

```
f=->n{0**n|n*f[n-1]}

```

## Test

```
irb(main):009:0> f=->n{0**n|n*f[n-1]}
=> #<Proc:0x25a6d48@(irb):9 (lambda)>
irb(main):010:0> f[125]
=> 188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```
> 2 votes

# Answer
# Husk, 2 bytes

### With Product (2 bytes)

```
Πḣ

```

```
    implicit parameter ⁰ (last argument)
 ḣ  get the range from 1 to n
Πḣ  get the product of that list

```

Try it online!

### With Fold (4 bytes)

```
F*1ḣ

```

```
       implicit parameter ⁰ (last argument)
   ḣ   get the range from 1 to n
F*1ḣ   fold left on multiplication starting with 1

```

Try it online!
> 2 votes

# Answer
# Rust, 48 bytes

```
fn f(n:f64)->f64{if n==0.0{1.0}else{n*f(n-1.0)}}

```

Try it online!

Standard recursive solution. Unfortunately the recursion means I can't save bytes by using a closure.

Note that this solution, along with almost every non python-based answer here, uses 64-bit floats, meaning large answers such as `125!` are calculated with some precision loss. This is more noticeable in rust than in, for example, JS, because JS prints the number in scientific notation, while rust prints the whole number.

# Rust with `num`, 61/85/102 bytes

```
fn f(n:i64)->BigInt{if n==0{1.into()}else{(n*f(n-1)).into()}}

```

Try it in Rust Playground

This answer is longer, but uses the `BigInt` type provided by the `num` crate and as a result calculates with maximum precision.

+24 bytes for a total of 85 if you want to count `use num::bigint::BigInt;`
or
+41 bytes for a total of 102 if you want to count `extern crate num;use num::bigint::BigInt;`

Rust Playground can be a little unpredictable, so if you get a timeout when trying to run this, keep trying. It should work eventually.
> 2 votes

# Answer
JavaScript, arbitrary precision, 18 bytes

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

```

This uses the bignum type for arbitrarily long integers.

```
f(125n) // 18826771768889260997437677024916008575954036487149…375565007131770880000000000000000000000000000000n

```

If you are content with doubles, only giving approximate results for $125!$, then you only need 17 bytes:

```
g=x=>x?x*g(x-1):1

```

We see that the `double` result is only accurate up to 22:

```
for(x=0;f(BigInt(++x))==BigInt(g(x)););x // 23

```
> 2 votes

# Answer
# Elixir, 41 Characters

I didn't see any Elixir implementation, so I gave it a try

```
f=&(for y<-0..&1,y>0,do: y)|>Enum.product

```

Generate an array from an array comprehension from 0 to X, while filtering on number strictly greater than 0, and pipe it to `Enum.product`

`Enum.product([])` returns 1, so it handle the case where our list empty when it filtered
> 2 votes

# Answer
# C#: 37

`int f(int n){return n>0?n*f(n-1):1;}`
> 1 votes

# Answer
## \>\<\>, 18 22

Launch with -v number for inputting the argument, or put it before the one.

Now also handles 0, some more intelligent direction usage, and some more space for putting numbers up to ff\* or 225:

```
   1&:?\&n;
:-1&*&:/?=0

```

Old version

```
 1&>:&*&\
;n&\?-1 /

```
> 1 votes

# Answer
# JavaScript, 41

```
function(n,r){for(r=1;n;r*=n--);return r}

```

or 39 if globals are okay.
> 1 votes

# Answer
**JAVA**

I rarely see Java solutions here. Why is that?

```
    public static void main(String[] args)
 {
     int tot = 1;
 for(int i = 1;i<=5;i++)
     tot *= i;
     System.out.println(tot);
}

```
> 1 votes

# Answer
## F# based on cfern's 63 36 characters

His didn't work on 125 for me. Adapted to use BigInteger

```
let f n:BigInteger=Seq.fold(*)BigInteger.One{BigInteger.One..n}

```

**Edit:** I just realized that double works too.

```
let f n:double=Seq.fold(*)1.{1.0..n}

```
> 1 votes

# Answer
### Scala, 39

```
def f(x:BigInt)=(BigInt(1)to x).product

```
> 1 votes

# Answer
## In Q (18 characters)

```
f:{(*/)9h$1+til x}

```

Computes in less than one millisecond.

```
q)\t f 125
0

```
> 1 votes

# Answer
# C++11 (35 chars)

Here's the function version:

```
int f(int x){return x?x*f(x-1):1;}

```

# C++11 template version (103 chars)

And here's the template version:

```
template<int I>struct f{static const int v=I*f<I-1>::v;};template<>struct f<0>{static const int v=1;};

```
> 1 votes

# Answer
# APL (13)

```
∇R←F X
R←×/ιX
∇

```

May need a `⎕IO←1` line to be sure ι starts at 1 - it's been awhile since I last used APL.
> 1 votes

# Answer
# Golfscript — 16

```
{.!+,{(}%{*}*}:f

```

The way I handle 0! is to do this trick: `.!+`:

* `0 + 0! = 0 + 1 = 1`
* `a + a! = a + 0 = a` (for every a != 0)

or:

```
{),{)}%);{*}*}:f

```

Here, I start of by increasing the argument by 1. But before I factor the array, I drop the last element.
> 1 votes

# Answer
# PHP, 41

```
function f($i){return $i==1?:$i*f($i-1);}

```
> 1 votes

# Answer
# C#, just the relevant code, 59

(assuming the argument variable is called a)

```
Enumerable.Range(1,int.Parse(a[0])).Aggregate(1,(x,y)=>x*y)

```

## With boilerplate, 122

```
using System.Linq;class A{static int Main(string[] a){return Enumerable.Range(1,int.Parse(a[0])).Aggregate(1,(x,y)=>x*y);}

```

(note that this solution returns the result)
> 1 votes

# Answer
# PARI/GP, 16 bytes

```
n->prod(i=2,n,i)

```

The shortest answer would be the native `!` which is disallowed.
> 1 votes

# Answer
# C 20 characters

```
x(){while(n)f*=n--;}

```

Assuming f and n are global variables. Here is the entire program :

```
double n=5,f=1;

x(){while(n)f*=n--;}

main(){
x();
printf("%f",f);
}

```
> 1 votes

# Answer
## Julia - 17

```
!n=n>1?n*!(n-1):1

```

This defines !n as !(n-1)\*n if n\>1, 1 otherwise. To make it work with big numbers you just need to make "n" a BigInt type (build in Julia).

And if its permitted (**13 chars.**):

```
!n=gamma(n+1)

```

with gamma equals to:

In the particular case that z its an integer the gamma function would be equal to:

Like its not a build in factorial it must not break the rules, but Im not posting it as solution just in case it does.
> 1 votes

# Answer
# C 37 characters

```
double f(int n){return n?n*f(n-1):1;}

```

This returns the value but is slightly longer than my
previous answer which used global variables.
> 1 votes

# Answer
# JavaScript (ES6) - 17 Characters

```
f=x=>x?x*f(x-1):1

```

Or:

```
f=x=>!x||x*f(x-1)

```

# JavaScript - 17 Characters (not a function)

```
for(a=1;n;)a*=n--

```

Assumes that the variable `n` contains the number you want the factorial for and outputs the answer to the console and stores it in the variable `a`.
> 1 votes

# Answer
the minimum solutions is already given using C# lamada. But just try to this another way.

```
        var seq = Enumerable.Range(1, 5).ToList();
        int O=1;    //O will contain Factorial or ouput
        seq.ForEach(x=>O*=x);

```
> 1 votes

# Answer
# TI-BASIC, ~~65~~ 14 bytes

```
For(I,0,Ans:IAns+not(Ans:End

```

Tricky tricky... `+not(Ans` and loop starting from zero should handle the special case. `seq(` isn't as viable of an option for that reason. TI-Basic only supports up to `10^100` which makes 70! and above fail, but it's easy to see that this solution would extend indefinitely.
> 1 votes

# Answer
**C#, 30**

```
double a=1;while(p>0){a*=p--;}

```

With spaces for ease of reading:

```
double a = 1;
        while(p > 0)
        {
            a *= p--;
        }

```

a is the factorial result, while p is the number for which factorial is computed.
> 1 votes

# Answer
# Python 2.7.5 - 29 characters

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

```

29 characters. It's still mathematically sound for a negative input value, since `(-n)! = ∞` and therefore the program gives a Runtime Error `maximum recursion depth exceeded`.
> 1 votes

# Answer
# Ruby: 22 characters

```
n.downto(1).reduce(:*)

```
> 1 votes

# Answer
## Simplefunge, 87 chars including whitespace

```
v

     v  *&<
     >   &V
     `    &
 v     <  o
     ^H^  @
v>>!1-^
>iV
  >1o@

```

I don't actually have time to test this right now, but it should work. If it doesn't work, I'll fix it tomorrow.
> 1 votes

# Answer
# Scala, 28 (39 w/ recursion)

Solution:

```
def f(n:Int)=(1 to n)product

```

Recursive solution:

```
def f(n:Int):Int=if(n<2)1 else n*f(n-1)

```
> 1 votes

# Answer
# R - 33

```
function(x) ifelse(x,prod(1:x),1)

> (function(x) ifelse(x,prod(1:x),1))(0)
[1] 1
> (function(x) ifelse(x,prod(1:x),1))(5)
[1] 120
> (function(x) ifelse(x,prod(1:x),1))(120)
[1] 6.689503e+198

```
> 1 votes

# Answer
## Powershell, 31

```
$a=1;$args[0]..1|%{$a=$_*$a};$a

```

## usage

```
powershell -nologo .\fact125.ps1 0
0
powershell -nologo .\fact125.ps1 1
1
owershell -nologo .\fact125.ps1 5
120
powershell -nologo .\fact125.ps1 125
1.88267717688893E+209

```
> 1 votes

# Answer
# Python, ~~43~~ 38

```
import math
f=lambda n:math.gamma(n+1)

```

**Explanation:** The gamma function is a very quickly-growing complex function which, at integer values, is equal to the factorial of one less than the number. So we add one to n and take the gamma function of it.

I hope this isn't considered cheating, since the gamma function is not technically able to directly calculate the factorial.
> 1 votes

# Answer
# Clojure/ClojureScript, 26 bytes

```
#(apply *(range 1(inc %)))

```
> 1 votes

# Answer
# Bash/coreutils/dc, 25

```
dc<<<"1 `seq -f%g* $1`p"

```

This forms a `dc` script and evaluates it. So ,with input of `5`, we evaluate

```
1 1*
2*
3*
4*
5*p

```

It took my machine 2.05 seconds to compute `10000!` here (that's factorial ten-thousand, with 36693 digits), so seems to scale reasonably well. For the zero case, `seq` produces no output, so the `dc` script is just `1 p` which produces the correct output `1`.
> 1 votes

# Answer
# PlatyPar, 8 bytes

```
c?1,_p\1

```

Try it online!

Explanation:

```
c?        ## if (n != 0)
  1,_p     ## product [1..n]
       \  ## else
        1  ## 1

```
> 1 votes

# Answer
# R 27 Bytes

```
function(n)prod(seq_len(n))

```
> 1 votes

# Answer
# , 9 chars / 19 bytes (noncompetitive)

```
+!ï⋎⨴⩤⁽1ï

```

`Try it here (Firefox only).`

Ay, 19th byte!

Great thing about this is that it also calculates factorials up to 171 instantly without returning Infinity.

## Bonus solution!

```
+!ï⋎⨴МĂ⩤⁽1ï

```

`Try it here (Firefox only).`

This one allows you to calculate past 171 without getting Infinity. Still superbly fast!
> 1 votes

# Answer
## JavaScript, 34 bytes

```
function f(n){return n?n*f(n-1):1}

```

*(or)*

```
function f(n){return n?n*f(--n):1}

```

### Explanation

Function takes in a value, returns itself multiplied by
**if n != 0:** the same function on the number decreased by one
**if n == 0:** 1

The final f(0) returns first with 1, times 1, times 2, etc.

Terminator removed, may upset *use strict*.
> 1 votes

# Answer
# Japt, 8 bytes

```
UòJ ¤r*1

```

Test it online!

### How it works

```
UòJ ¤r*1   // Implicit: U = input integer                5
UòJ        // Create the inclusive range [-1..U].        [-1, 0, 1, 2, 3, 4, 5]
    ¤      // Slice off the first two items.             [1, 2, 3, 4, 5]
     r*1   // Reduce by multiplication, starting at 1.   1*1=1*2=2*3=6*4=24*5=120
           // Implicit output                            120

```
> 1 votes

# Answer
# Lua, 47 bytes

```
function f(n)return(n<1 and 1 or n*f(n-1))end

```
> 1 votes

# Answer
# PHP

## Short, 58

```
<?$r=$i=$argv[1];while($i>1){$i--;$r=$r*$i;}echo($r==0?1:$r);

```

### Tests

0 -\> `1`

1 -\> `1`

5 -\> `120`

125 -\> `1.8826771768889E+209`

170 -\> `7.257415615308E+306`

171 -\> `INF`

*Executes in microseconds.*

### Ungolfed

```
<?php
$r = $i = $argv[1]; // Set $r and $i to Arg.
while($i > 1) // Calculate while $i bigger than 1
{
    $i--; // Decrement $i (so it's not infinite)
    $r = $r * $i; // Calculation the Factorial
 }
 echo ($r==0 ? 1: $r); // Output and make 0! = 1
 ?>

```

## Slighty Longer, 86

```
<?$r=$i=(isset($argv[1])?$argv[1]:0);while($i>1){$i--;$r=$r*$i;}echo($r==0?1:$r)."\n";

```

### Improvements

* Output with `\n`
* Doesn't throw error if no arg defined
> 1 votes

# Answer
# DUP, 19 bytes

```
[$[$1-a;!*][%1]?]a:

```

`Try it here!`

A recursive lambda that leaves result on the stack. Usage:

```
6[$[$1-a;!*][%1]?]a:a;!

```

# Explanation

```
[               ]a: {set a to lambda}
 $                  {check if top of stack >0}
  [       ][  ]?    {conditional}
   $1-a;!*          {if so, top of stack *a(top of stack -1)}
            %1      {otherwise, replace top of stack with 1}

```
> 1 votes

# Answer
## Hoon, 29 bytes

```
|=(@ (reel (gulf [1 +<]) mul)

```

Hoon's native number is a bignum, so it works fine with 125 (or even 2000). It also correctly gives 1 for 0.

It uses `+<` in order to access the sample of the gate. This is axis navigation syntax: It means to access the tail of the subject, and then the head, which is where the sample is stored in the binary tree model Hoon uses.

Urbit drops you into a shell and Hoon REPL when you start it, :dojo. To test this, simply enter `%. 125` on one line and then the snippet for 125! Note there are two spaces between the dot and 1.
> 1 votes

# Answer
# Yup, ~~33~~ 31 29 bytes

```
*{{:0e-}]~{~|~|0~--e~}~#\}0e#

```

Here's the github. Invoke like this:

```
node yup.js <location>.yup -n <input>

```

Or

```
node yup.js -l "*{{:0e-}]~{~|~|0~--e~}~#\}0e#" -n <input>

```

or Try it online!

Examples:

```
λ node yup.js -l "*{{:0e-}]~{~|~|0~--e~}~#\}0e#" -n 5
120
λ node yup.js examples\factorial.yup -n 0
1

```

## Explanation

```
*{{:0e-}]~{~|~|0~--e~}~#\}0e#
*                              ` take input
 {                       }     ` while TOS -- if zero, we advance to the }
                          0e#  ` print number 1 (exp(0))
                               ` otherwise (nonzero)
  {    }                       ` while TOS is not zero
   :                           ` duplicate TOS
    0                          ` push 0
     e                         ` pop 0, push exp(0) = 1
      -                        ` subtract 1
                               ` we eventually are at zero.
        ]                      ` we move that zero to the bottom of the stack
         ~                     ` switch top two for looping offset
          {~        ~}         ` while STOS
            |~|0~--e           ` multiply two elements (see further down)
                      ~        ` switch the top zero with the result
                       #       ` print the result
                        \      ` exit program (so we don't print the final one)

```

### Multiplication

In this program, I have multiplication defined as thus:

```
|~|0~--e

```

First, observe `0~--`. This pushes a zero behind the TOS, and subtracts twice:

```
command | stack
        | a b
0       | a b 0
~       | a 0 b
-       | a (-b)
-       | a - (-b) = a + b

```

This performs addition. Let's replace `0~--` with `+` for clarity:

```
|~|+e

```

Now, `|` is `ln`. So watch the stack:

```
command | stack
        | a b
|       | a ln(b)
~       | ln(b) a
|       | ln(b) ln(a)
+       | (ln(b)+ln(a))
e       | exp(ln(b)+ln(a))

```

And, by the theorem of logarithms, this is multiplication.
> 1 votes

# Answer
# Desmos, 18 bytes

```
a=1
\prod _{n=1}^an

```

Uses the formula for a! instead of a!
> 1 votes

# Answer
# Joy, 13 bytes

```
[1][*]primrec

```

30 char requirement in codegolf?
> 1 votes

# Answer
# Maple, 17 bytes

```
n->`*`(seq(1..n))

```

Usage:

```
> f:=n->`*`(seq(1..n));
> f(0);
  1
> f(5);
  120
> f(125);
  188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```
> 1 votes

# Answer
# Fourier, 18 bytes

```
1~NI(i^~iN*i~Ni)No

```

**Try it online!**
> 1 votes

# Answer
## Oasis, 3 bytes

Try it online

```
n*1

```

Explanation:

```
n*1
n    Push n
 *   Multiply the two items on the top of the stack
     Because there is only one item on the stack, A(n - 1) is pushed
     Implicit output
  1  Special case A(0) = 1

```
> 1 votes

# Answer
# Pushy, 3 bytes

```
RP#

```

Explanation:

```
R  \ Push the inclusive range of the input
P  \ Push the product
#  \ Print

```

**Try it online!**
> 1 votes

# Answer
## Alice, 13 bytes

```
/o
\i@/r.1~&*

```

Try it online!

### Explanation

This is a basic framework for arithmetic programs to read and write integer I/O and process them in Cardinal mode:

```
/o
\i@/...

```

As for the actual computation:

```
r    Range: Replace the input N with 0, 1, 2, ..., N.
.    Duplicate N.
1~   Put a 1 underneath the copy to initialise the product correctly
     for N = 0.
&    Repeat the next command N times.
*    Multiply (N times, multiplying up the entire stack).

```
> 1 votes

# Answer
## Powershell, 38 bytes

```
filter f{((1..$_-join'*'|iex),1)[!$_]}

```

I used some of the other answers here for inspiration, but I'm not lower than @Joey. Although, I'm not sure how their code knows to stop subtracting once it hits 0...

```
PS C:\> 0|f
1
PS C:\> 4|f
24
PS C:\> 125|f
1.88267717688893E+209

```
> 1 votes

# Answer
**Pyth, 15**

`K1FNr1hQ=K*KN;K`

Try it here!

If you only need one variable, it’s better to use **K** or **J** which don’t need an equals sign to be assigned to on their first use
> 1 votes

# Answer
**Pyth, 7 Bytes**

```
u*GhHQ1

```

Try it online!

This is pretty much simple. Pyth is a good choise for code golfing.
> 1 votes

# Answer
# Pyth, 3 bytes

```
*FS

```

**Try it here.**
> 1 votes

# Answer
# K (oK), 5 bytes

**Solution:**

```
*/1+!

```

Try it online!

**Explanation:**

Interpretted right-to-left:

```
*/1+!   / solution
    !   / til, performs range, 0..n
  1+    / adds 1 (vectorised)
*/      / multiply-over elements in list

```

**Notes:**

Unlike the K/Kona/Q implementations, the input is treated as a float:

```
oK)@5
-9
q)type 5
-7h

```
> 1 votes

# Answer
# dc, ~~23~~ 22 bytes

```
1r[dk*K1-d0<a]dsax_1*+

```

Try it online or verify 0-125!

### Explanation

```
1r[dk*K1-d0<a]dsax_1*+  # input on stack, eg:     4
1                       # push 1:                 1 4
 r                      # reverse top two:        4 1
  [dk*K1-d0<a]          # push [string]:          [string] 4 1
              dsa       # copy top to register a: [string] 4 1
                 x      # exec top*               0 24
                  _1    # push -1:                -1 0 24
                    *   # multiply:               0 24
                     +  # add:                    24

# first exec of [string]:

  [dk*K1-d0<a]  # stack:                4 1
   d            # duplicate top:        4 4 1
    k           # pop & set precision:  4 1
     *          # multiply              4
      K         # push precision        4 4
       1        # push 1                1 4 4
        -       # subtract              3 4
         d0<a   # if top > 0 exec content of register a, namely [string]
                # output on stack:      24

```

In case of `0` after the exec part (`*`), the stack will be `-1 0`:

```
x       # exec top*               -1 0
 _1     # push -1:                -1 -1 0
   *    # multiply:               1 0
    +   # add:                    1

```
> 1 votes

# Answer
# Pyt, ~~1~~ 2 bytes

```
řΠ

```

Try it online!

```
Implicit input
ř creates a range from 1 to input, taking care of the 0 edge case
Π multiplies everything together
Implicit output

```
> 1 votes

# Answer
# AsciiDots, ~~80~~ ~~57~~ ~~53~~ ~~49~~ ~~48~~ ~~47~~ 43 bytes

```
/{*}<$#&
\<^\*#1\
 \1#~*{-}-\
/#1/\*.>#?)
.

```

Outgolfs the sample by ~~34~~ ~~57~~ ~~61~~ ~~65~~ ~~66~~ ~~67~~ 71 bytes. Try it online!
> 1 votes

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

### Results

```
$ time bash -c 'for i in 0 1 2 3 4 125 1000; do ./607.dc <<<$i | tr -dc "[0-9]"; echo; done'
1
1
2
6
24
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

real    0m0.014s
user    0m0.015s
sys     0m0.004s

```
> 1 votes

# Answer
# µ6, 14 bytes

```
#+[#.[#/0[+/1]/1/2][+/0]/1]

```

Try it online!

## Explanation

```
#                            -- primitive recursion with
 +                           -- | base case: successor (of 0)
  [                          -- | compose
   #.[#/0[+/1]/1/2]          -- | | multiplication
                   [+/0]     -- | | successor of first argument
                        /1   -- | | second argument
                          ]  -- | : f n * f (n-1)

```
> 1 votes

# Answer
# Powershell, 21 byte

```
1..$_-ge1-join'*'|iex

```

Test script:

```
$f = {
1..$_-ge1-join'*'|iex
}

@(
    0,1,2,3,4,5,6,125
) | % {
    &$f $_
}

```

Output:

```
1
1
2
6
24
120
720
1.88267717688893E+209

```

## Explanation

1. `1..$_` generates a sequence of integer from 1 to argument (sequence=(1,0) if argument equal to 0)
2. `-ge1` leaves in the sequence numbers `great or equal to 1`
3. `-join'*'` converts the sequence to string with '\*' between elements
4. `|iex` evaluates string as powershell expression
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# CJam, 10 bytes

```
qi1{_(j*}j

```

Explanation:

```
qi1{_(j*}j
qi            e# Read input as integer
   {    }j    e# Define a recursive function
  1           e# Where the value for f(0) = 1
    _         e# For f(i), duplicate i
     (        e# Then subtract 1
      j       e# Run the function for this number (i-1)
       *      e# Multiply i and f(i-1) together
              e# Implicit output

```

Try it online!
> 1 votes

# Answer
# MathGolf, 3 bytes

```
╒ε*

```

Try it online!

## Explanation

```
╒    create 1-based range [1, ..., input]
 ε*  Reduce by multiplication

```
> 1 votes

# Answer
# Clam, ~~9~~ 7 bytes

```
p;#qB1Q

```

*-2 bytes thanks to ASCII-only*

## Explanation

```
p;#qB1Q - Implicit Q = first input
p       - Print...
 ;      - Product of...
    B1Q - Range(1...Q) OR Range(Q...1) if (Q < 1)
  #q    - Where (q => q) ie (q != 0)

```
> 1 votes

# Answer
# \>\<\>, 14 bytes

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

```

Try it online!
> 1 votes

# Answer
# 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`.
> 1 votes

# Answer
# 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
> 1 votes

# Answer
# 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
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Pepe, 60 bytes

```
rrEERREeeeeeeeErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE

```

Try it online!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Julia, 14 characters

```
f(n)=prod(1:n)

```

although I think recursive implementations are more interesting for this challenge. The best I could do there was 18 characters:

```
f(n)=n<1||n*f(n-1)

```

for `n = 125`, note that one has to use a `BigInt` like this:

```
julia> f(big(125))
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

```

Both complete in much less than a second.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Wren, 34 bytes

Generate range from a to 1 and then reduce it with product of this whole sequence.

```
Fn.new{|a|(a..1).reduce{|a,b|a*b}}

```

Try it online!
> 1 votes

# Answer
# Keg, ~~9~~ ~~5~~ 4 bytes

```
Ï⑨∑*

```

Try it online!

-1 byte thanks to @A̲̲

## Answer History

### 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
> 1 votes

# Answer
## , 8 bytes

```
#*¨1^ň

```

## Explanation

```
     ň Input a single number from STDIN
    ^  Increment this number
  ¨1   Exclusive range from 1 to this number
#*     Fold multiplication over this vector

```
> 1 votes

# Answer
## , 5 bytes

```
*R:e+

```

## Explanation

```
*R    % Reduce by the product
  :e  % Is this item 0?
    + % Add this value to the product
      % We need to also calculate fact(0)
      % Implicit output

```
> 1 votes

# Answer
# C (gcc), 33 bytes

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

```

Output:

```
1
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
51090942171709440000
1124000727777607680000
25852016738884978212864
620448401733239409999872
15511210043330986055303168
403291461126605650322784256
10888869450418351940239884288
304888344611713836734530715648
8841761993739700772720181510144
265252859812191032188804700045312
8222838654177922430198509928972288
263130836933693517766352317727113216
8683317618811885938715673895318323200
295232799039604119555149671006000381952
10333147966386144222209170348167175077888
371993326789901177492420297158468206329856
13763753091226343102992036262845720547033088
523022617466601037913697377988137380787257344
20397882081197441587828472941238084160318341120
815915283247897683795548521301193790359984930816
33452526613163802763987613764361857922667238129664
1405006117752879788779635797590784832178972610527232
60415263063373834074440829285578945930237590418489344
2658271574788448529134213028096241889243150262529425408
119622220865480188574992723157469373503186265858579103744
5502622159812088456668950435842974564586819473162983440384
[encoded data, 10447 characters]

```

Try it online!
> 1 votes

# Answer
# MAWP, 31 bytes

```
%@<:.>!!1A[1A~!1A~]%1A[1A~W~]%:

```

125! takes around 11 seconds, so it fulfills the criteria.

Try it!
> 1 votes

# Answer
# MAWP, 19 bytes

```
|[!1A]%_1A[%W_1A]~:

```

Utilises this input/output consensus that numbers can be taken as ascii characters.

# MAWP, 19 bytes

```
@[!1A]%_1A[%W_1A]~:

```

Try it!

If you want to enter normal numbers like normal people.
> 1 votes

# Answer
# Lua (LuaJIT), 36 bytes

```
x=1 for i=1,...do x=x*i end print(x)

```

Try it online!

Because who needs recursion anyways?

I'm using LuaJIT instead of mainline Lua because Lua 5.3+ would make `x` 64-bit signed integer (and, sadly, LuaJIT implements Lua 5.1), making code fail on big values. It costs single byte to fix it:

# Lua, 37 bytes

```
x=1. for i=1,...do x=x*i end print(x)

```

Try it online!

Now it's double again.
> 1 votes

# Answer
# JavaScript (V8), 17 bytes

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

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
ɾΠ

```

Range of 1 to input and product

Try it!
> 1 votes

# Answer
# RickRoll-Lang, ~~164~~ ~~160~~ 96 bytes

eval too op lol

```
takemetourheart
ijustwannatelluhowimfeeling eval("*".join(map(str,[1,*range(1,int(input())+1)])))

```

### Explanation:

RickRoll-Lang keywords do not need spaces between them

`takemetourheart` =\> main function declaration

`ijustwannatelluhowimfeeling eval("*".join(map(str,[1,*range(1,int(input())+1)])))` =\> print the evaluated result of joining "\*" a mapping of string to each item in a list of 1 and the range from \[1, n)

=\> implicit say goodbye (end block)

Try it online!
> 1 votes

# Answer
# x86 32-bit machine code, 69 bytes

```
\x6a\x01\x58\x89\x03\x89\xc1\xc1\xe1\x02\x29\xcc\x89\xe7\x89\xde\xf3\xa4
\x89\xc5\x89\xd1\x49\x7e\x25\x31\xf6\x89\xf7\xf7\xdf\x8b\x3c\xb4\x11\x3c
\xb3\x19\xff\x46\x39\xee\x7c\xf1\xf7\xdf\x74\x07\x83\x04\xb3\x01\x46\x72
\xf9\x39\xf0\x0f\x4c\xc6\xeb\xd8\x8d\x24\xac\x4a\x7f\xc1\xc3

```

Try it online!

Unlike other machine code entries, I implemented arbitrary-precision multiplication from scratch.

The algorithm is the most basic one. For \\$a × b\\$, \\$a\\$ is added \\$b\\$ times with a loop. It doesn't scale well for really big numbers, but 125! is calculated within 0.3 seconds (user time) in TIO.

The function outputs an arbitrary-precision integer in base \\$2 ^ {32}\\$. The challenge doesn't require the function to output a string, so I can use any external method to convert the output to printable string apart from the challenge. The huge footer in TIO is the source code of mini-GMP that I copy-pasted for bignum-to-decimal-string conversion. TIO has GMP, but only for 64-bit, unfortunately.

---

The code is quite straightforward. Here is a pseudocode to illustrate what the assembly code is doing.

```
for x = y!:
  x = 1
  i from y to 1:
    z = x
    j from y - 1 to 1:
      x += z

```

**assembly (nasm)**

```
; input: edx, output: ebx (bignum array), eax (number of "limbs")
; custom calling convention, everything except `ebx` and `esp` gets dirty
_fac:
    push 1
    pop eax
    mov [ebx], eax
.L0:
    mov ecx, eax
    shl ecx, 2
    sub esp, ecx
    mov edi, esp
    mov esi, ebx
    rep movsb
    mov ebp, eax
    mov ecx, edx
.L1:
    dec ecx
    jle .1
    xor esi, esi
    mov edi, esi
.L2:
    neg edi
    mov edi, [esp + esi * 4]
    adc [ebx + esi * 4], edi
    sbb edi, edi
    inc esi
    cmp esi, ebp
    jl .L2
    neg edi
    jz .0
.L3:
    add dword [ebx + esi * 4], 1
    inc esi
    jc .L3
.0:
    cmp eax, esi
    cmovl eax, esi
    jmp .L1
.1:
    lea esp, [esp + ebp * 4]
    dec edx
    jg .L0
    ret

```
> 1 votes

# Answer
# rusty\_deque, 25 bytes

```
1~+~1~{*~}~1~rot!2~range~

```

Expects a non-negative integer `n` on the deque, and a clean deque.

### Explanation

```
# given an int n (n -- n!)
1~ +~  # exclusive end for range
1~     # guard for final multiplication
{*~}~  # loop body: multiply the right two numbers
1~     # index step
rot!   # ending index (n+1), rotate from the front of the deque
2~     # starting index
range~ # for i in range(2, n+1, 1)...

```

A version that doesn't assume a clean deque, **29 bytes**:

```
1~+~rot~1~{*~}~1~rot!2~range~

```

### Explanation

```
# given an int n (n -- n!)
1~ +~  # exclusive end for range
rot~   # save the range end at the front of the deque
1~     # guard for final multiplication
{*~}~  # loop body: multiply the right two numbers
1~     # index step
rot!   # ending index (n+1), bring the range end back
2~     # starting index
range~ # for i in range(2, n+1, 1)...

```
> 1 votes

# Answer
# Ruby, 25 bytes

```
f=->(n){n!=0?n*f.(n-1):1}
```

Ruby's lambda function is a bit verbose than it should have been.

Attempt This Online!
> 1 votes

# Answer
# J-uby, 15 bytes

```
:+|:+&[1]|:/&:*

```

Try it online!
> 1 votes

# Answer
# **JavaScript**, 17 bytes

```
f=n=>!n||n*f(n-1)

```
> 1 votes

# Answer
# RASEL, 22 bytes

```
1&\:?v:1-3\-/
1\/.@>-1

```
> 1 votes

# Answer
# Python 2, ~~59~~ 55 bytes

```
lambda x:reduce(lambda a,b:a*b,range(1,x+1))if x else 1

```

This solution uses Python 2 because `reduce` is built-in, in Python 3, it's part of `functools`. This solution is iterative, and it works for values larger than 100.

-4 by Steffan
> 1 votes

# Answer
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
ra

```

See the README to see how to run this

```
ra # Takes a num as input
 a # Range [1, n]
r  # Product

```
> 1 votes

# Answer
# Chocolate, 2 bytes

```
ΠỌ

```

Try it online!

Product of range \\$\[1, n\]\\$.

Or, using a builtin overload of product:

# Chocolate, 1 byte

```
Π

```

Try it online!
> 1 votes

# Answer
# Vyxal 3, 3 bytes

```
Ω}Π

```

Try it Online!

-2 bytes thanks to @lyxal

### Explanation (outdated):

```
[ɾΠ|1
[      ## If the input is 1 or greater:
  Π    ## Product of
 ɾ     ## Range [1..n]
   |1  ## Else 1

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Kotlin, 46 bytes

```
{x:Int->x.downTo(1).reduceOrNull{a,i->a*i}?:1}

```

Bit of a shame that we need that type hint...

Attempt This Online!
> 1 votes

# Answer
# Python (31 29 character)

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

```

28 characters

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

```
> 0 votes

# Answer
**MuPAD – 7**

```
`*`($n)

```

Computes `n!`, no recursion.
> 0 votes

# Answer
# Python 3 - 52 characters

```
r=n=int(input())
for i in range(1,n):r=r*i
print(r)

```

This is my best try. My C++ solution (not posted) was over 100 characters even without `#include`s and whitespace!
> 0 votes

# Answer
# Clojure, 29

```
#(reduce * (range 1 (inc %)))

```
> 0 votes

# Answer
# Befunge-93, ~~24~~ 22

```
0\0>-#1:_$> #\:#*_$:!+

```

As with the other Befunge answer(s?), this is a function in that you enter with your input on the top of the stack, start on the top-left with your pointer facing right, and exit still facing right with the result on top of the stack.

The difference is that this one is shorter, and only one row. And it still doesn't use wraparound or self-modification.

You can test it here. Testing six factorial:

```
6    0\0>-#1:_$> #\:#*_$:!+    .@

```

Outputs 720.

Testing zero:

```
0    0\0>-#1:_$> #\:#*_$:!+    .@

```

Outputs 1. The `:!+` (formerly `:0`!+`) does at the end does nothing but check for zeroes.

**EDIT:** A suggestion golfed two characters off. Thanks!
> 0 votes

# Answer
# , 10 bytes

Try it here!

```
jC:t:tF|*p

```

A three-link program. Ungolfed:

```
j C :t :t F |* p

```

`j` takes numeric input, `C` begins a new link, `:t` duplicates and decrements to `[n n-1]`; the `:t:t` becomes `[n n-1 n-2]`; the last `n-2` is popped for a zero-check by the `F` node; once a zero is found, we continue. `|*` folds the stack over multiplication, and `p` prints it.
> 0 votes

# Answer
# ForceLang, 83 bytes

Noncompeting, language postdates the challenge

```
set a io.readnum()
set b 1
label l
set b b.mult a
set a a+-1
if a
goto l
io.write b

```
> 0 votes

# Answer
## Perl 5, 31 bytes

```
$s=1;map{$s*=$_}(2..<>);print$s

```

Prints the result in scientific notation, and takes care of the 0 value as well.

Another way to do it, but without the 0 case, for **26 bytes** :

```
print eval join'*',(1..<>)

```
> 0 votes

# Answer
## Pyke, 2 bytes

```
SB

```

Try it here!

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

```
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# Mathcad, tbd "bytes"

---

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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
## Neoscript, 31 bytes

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

```
> 0 votes

# Answer
## Logy, 47 bytes

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

```

Trivial. Return the product of the range `[2..n]`
> 0 votes

# Answer
# Tcl, ~~41~~ ~~37~~ 35 bytes

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

```

Try it online!
> 0 votes

# Answer
# 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
> 0 votes

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

```
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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)
> 0 votes

# Answer
# 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`
> 0 votes

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

```
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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)
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# Kotlin, ~~50~~ 45 bytes

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

```

Thanks to @jonathan-frech
> 0 votes

# Answer
# Python 3, 32 29 bytes

```
lambda n:n*f(n-1)if n>0else 1

```

Try it online! Just a simple recursive solution I made for Generalised multi-dimensional chess knight's moves.

Thanks for the -3 Maanas
> 0 votes

# Answer
# Dyalog APL, 1 char

```
!

```

! is a primitive function in Dyalog APL: in the monadic case (right argument only) gives the factorial of the right argument

https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtExQNuKAMQxjDFC6CkDP9/x8A
> 0 votes

# Answer
# GNU bc, 40 bytes

```
define f(n){for(j=1;n;)j*=n--
return j}

```

Try it online!

# bc, 43 bytes

```
define f(n){
for(j=1;n;n--)j*=n
return(j)}

```

Try it online!
> 0 votes

# Answer
# Flobnar, 17 bytes

```
>-::
>1*_
\@<^
&:

```

Try it online!

Individually developed as part of LYAL on 2022-07-06, and it happens to beat JoKing's 19 bytes.

### How it works

```
\@    Start at @, facing left
&     \ pushes & (decimal input) to the call stack (call it n)
      and keep evaluating left
:
_>1   Horizontal if: if n (:) is 0, evaluate to right (1), otherwise
^

  :
  *   Multiply n (:) with the result of recursive function call
\ <   (& fails and falls through to south)
&:    called with n-1
>-
 1

```
> 0 votes

# Answer
# Thunno, \\$ 4 \log\_{256}(96) \approx \\$ 3.29 bytes

```
R1+P

```

Attempt This Online!

But, if built-ins were allowed:

```
F

```

Attempt This Online!

#### Explanation

```
R1+P  # Implicit input
R     # range(0, input)
 1+   # increment
   P  # product
      # (for an empty list
      # this gives 1)
      # Implicit output

```
> 0 votes

# Answer
# Itr, 4 bytes

`1#R*`

online interpreter

## Explanation

```
1     ; push 1
 #    ; read a number from standard input
  R*  ; reduce the range from 1 to that number with * as operator
      ; implicitly print the result of the reduction or the 1 if the range was empty

```

---

# Itr, 2 bytes:

`#P`

Product over the range from 1 to the input. (could be considered a factorial built-in)
> 0 votes

# Answer
# ARBLE, 16 bytes

```
range(1,n)/(x*y)

```

Reduce the range of 1-n by `x*y`.

Try it online!
> 0 votes

# Answer
# VBA, 55 Bytes

Subroutine that takes input \\$n\\$ and outputs \\$n!\\$

```
Function f(n)
If n Then f=n*f(n-1)Else f=1
End Function

```
> 0 votes

# Answer
# Yabasic, 60 bytes

Port of VBA answer.

```
Sub f(n)
If n Then Return n*f(n-1)Else Return 1EndIf
End Sub

```

Try it online!
> 0 votes

# Answer
# Google Sheets, 26 Bytes

Anonymous worksheet function that takes input, \\$n\\$, from cell `[A1]` and outputs \\$n!\\$ to the calling cell.

```
=Product(Sequence(Max(A1,1

```

# Excel Version, 29 Bytes

Listed separately as Excel throws an error for unpaired parens.

```
=PRODUCT(SEQUENCE(MAX(A1,1)))

```
> 0 votes

---
Tags: code-golf, arithmetic, restricted-time, factorial
---