# Find the Factorial!

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

The factorial, represented with ! is defined as such

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

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

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

Requirements:

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

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

• How many of the given answers can actually compute up to 125! without integer overflow? Wasn't that one of the requirements? Are results as exponential approximations acceptable (ie 125 ! = 1.88267718 × 10^209)?
– Ami
Feb 6, 2011 at 22:43
• @SHiNKiROU, even golfscript can manage 125! less than 1/10th of a second and it's and interpreted interpreted language! Feb 8, 2011 at 3:21
• Completes in under a minute seems a very hardware-dependent requirement. Completes in under a minute on what hardware? Aug 24, 2017 at 18:05
• @sergiol Incredibly that hasn't been an issue in the last 2 years, I suspect most languages can get it done in under a minute. Aug 24, 2017 at 21:20
• Why aren't built-ins allowed? You haven't specified what built-ins are, and if you said that it was up to a "reasonable person" to decide (which is completely subjective, but ignoring that), you still say that any form of eval is a built-in for the factorial, even though it evaluates code, not the factorial of a given number. May 7, 2019 at 2:02

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

# PHP, 41

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


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


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

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

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

• But will this provide the full numeric value of 125!? Nov 5, 2014 at 1:37
• @WallyWest yes, JavaScript has only one numeric type, Number. It is not arbitrary precision, but it can hold up to 170! Before overflow, at which point it is said to be Infinity. JS is weird?, but it is actually helpful in this case. Feb 5, 2016 at 6:51
• Wow... I just looked at the similarities between my code and yours. Ours are basically the same. Jun 8, 2016 at 19:30

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


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

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.

• Couldn't you just say "while(p)statement;" instead of "while(p>0){statement;}"? Unless C# behaves differently from C, it should work. Apr 1, 2014 at 18:59
• if p is bool, it would. Here I need to continue checking p with 0... Apr 2, 2014 at 5:20

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

# Ruby: 22 characters

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


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

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


# 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


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

• This doesn't account for 0!=1. You can use the Invoke-Expression command to evaluate on-the-fly, and then use bool casting to select the appropriate answer -- try param($a)$b=1..$a-join'*'|iex;($b,1)[!$a] for 41 bytes Nov 23, 2015 at 20:13 • Actually, we can move the |iex and skip the $b entirely -- 37 Bytes for param($a)((1..$a-join'*'),1)[!$a]|iex Nov 23, 2015 at 20:38 # 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. • To quote Wikipedia, "In mathematics, the gamma function is an extension of the factorial function, with its argument shifted down by 1, to real and complex numbers". Some would say it's "close enough" to a factorial function that it shouldn't count, I personally don't care because it's longer than the other Python answers. Oct 14, 2015 at 17:49 # Clojure/ClojureScript, 26 bytes #(apply *(range 1(inc %)))  # Bash/coreutils/dc, 25 dc<<<"1 seq -f%g*$1p"


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.

# R 27 Bytes

function(n)prod(seq_len(n))


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

• ⎕IO←1 is default in many APLs. Also, you can save 3 bytes: Remove the ∇ and the last line break, giving the ⎕CR instead of the ⎕VR. Typo: * should be ×. The former is Power: n*2 = n².
Jan 25, 2016 at 14:35

# PlatyPar, 8 bytes

c?1,_p\1


Explanation:

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

• This does not seem to handle the special 0 case. Jan 26, 2016 at 4:04
• @ՊՓԼՃՐՊՃՈԲՍԼ oops, I completely forgot. Adding... Jan 26, 2016 at 4:46

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

• There were already some similar answers but uses ES6. Jan 26, 2016 at 22:42

# Japt, 8 bytes (non-competing)

This answer is non-competing because Japt was created long after this challenge.

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

• This does not handle the zero case correctly (0! should return 1). Jan 27, 2016 at 3:40
• @ՊՓԼՃՐՊՃՈԲՍԼ Thanks, fixed now. Jan 27, 2016 at 23:21
• I know this is old but, wouldn't á be enough? Aug 7, 2018 at 17:51
• @LuisfelipeDejesusMunoz I think you mean l, but yes :-) Aug 8, 2018 at 15:30

# 𝔼𝕊𝕄𝕚𝕟, 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!

• Mind explaining how this gets around Infinity? :) Jan 27, 2016 at 18:30
• МĂ is math.js's bignumber function. Jan 27, 2016 at 23:07

# Lua, 47 bytes

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


# PARI/GP, 16 bytes

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


The shortest answer would be the native ! which is disallowed.

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


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

• Hoon is a beautiful mystery.
– Lynn
Mar 1, 2016 at 1:10
• It's a surprisingly nice language to code in! It takes a little bit to learn all the runes, but you don't even need to internalize them to read it since they belong in "families" based on the first symbol. The fact it's strongly typed and has a novel type system is just icing on the cake. Mar 1, 2016 at 1:36

# Desmos, 18 bytes

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

Uses the formula for a! instead of a!