92
\$\begingroup\$

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

The factorial, represented with ! is defined as such

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

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

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

Requirements:

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

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

\$\endgroup\$
12
  • 15
    \$\begingroup\$ How many of the given answers can actually compute up to 125! without integer overflow? Wasn't that one of the requirements? Are results as exponential approximations acceptable (ie 125 ! = 1.88267718 × 10^209)? \$\endgroup\$
    – Ami
    Commented Feb 6, 2011 at 22:43
  • 7
    \$\begingroup\$ @SHiNKiROU, even golfscript can manage 125! less than 1/10th of a second and it's and interpreted interpreted language! \$\endgroup\$
    – gnibbler
    Commented Feb 8, 2011 at 3:21
  • 8
    \$\begingroup\$ Completes in under a minute seems a very hardware-dependent requirement. Completes in under a minute on what hardware? \$\endgroup\$
    – sergiol
    Commented Aug 24, 2017 at 18:05
  • 4
    \$\begingroup\$ @sergiol Incredibly that hasn't been an issue in the last 2 years, I suspect most languages can get it done in under a minute. \$\endgroup\$ Commented Aug 24, 2017 at 21:20
  • 5
    \$\begingroup\$ 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. \$\endgroup\$
    – MilkyWay90
    Commented May 7, 2019 at 2:02

217 Answers 217

1 2 3
4
5
8
1
\$\begingroup\$

Scala, 39

def f(x:BigInt)=(BigInt(1)to x).product
\$\endgroup\$
1
\$\begingroup\$

In Q (18 characters)

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

Computes in less than one millisecond.

q)\t f 125
0
\$\endgroup\$
1
  • \$\begingroup\$ f:{prd 1f+til x} for 16. f:{prd 1f+(!)x} for 15. \$\endgroup\$
    – mkst
    Commented Sep 13, 2017 at 7:44
1
\$\begingroup\$

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}
\$\endgroup\$
1
  • \$\begingroup\$ 63 -> 36 is simply beautiful. "I reverse the floating point usage, you reverse your byte count!" \$\endgroup\$ Commented Sep 30, 2020 at 19:00
1
\$\begingroup\$

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

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.

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

PHP, 41

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

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

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.

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

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:

gamma

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

enter image description here

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.

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

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.

\$\endgroup\$
3
  • \$\begingroup\$ But will this provide the full numeric value of 125!? \$\endgroup\$ Commented Nov 5, 2014 at 1:37
  • \$\begingroup\$ @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. \$\endgroup\$
    – Cyoce
    Commented Feb 5, 2016 at 6:51
  • \$\begingroup\$ Wow... I just looked at the similarities between my code and yours. Ours are basically the same. \$\endgroup\$ Commented Jun 8, 2016 at 19:30
1
\$\begingroup\$

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

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)

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

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.

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

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.

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

Ruby: 22 characters

n.downto(1).reduce(:*)
\$\endgroup\$
1
\$\begingroup\$

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.

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

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

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

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
\$\endgroup\$
2
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Nov 23, 2015 at 20:13
  • 1
    \$\begingroup\$ Actually, we can move the |iex and skip the $b entirely -- 37 Bytes for param($a)((1..$a-join'*'),1)[!$a]|iex \$\endgroup\$ Commented Nov 23, 2015 at 20:38
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Oct 14, 2015 at 17:49
1
\$\begingroup\$

Clojure/ClojureScript, 26 bytes

#(apply *(range 1(inc %)))
\$\endgroup\$
1
\$\begingroup\$

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.

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

R 27 Bytes

function(n)prod(seq_len(n))
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ ⎕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². \$\endgroup\$
    – Adám
    Commented Jan 25, 2016 at 14:35
1
\$\begingroup\$

PlatyPar, 8 bytes

c?1,_p\1

Try it online!

Explanation:

c?        ## if (n != 0)
  1,_p     ## product [1..n]
       \  ## else
        1  ## 1
\$\endgroup\$
2
  • \$\begingroup\$ This does not seem to handle the special 0 case. \$\endgroup\$ Commented Jan 26, 2016 at 4:04
  • \$\begingroup\$ @ՊՓԼՃՐՊՃՈԲՍԼ oops, I completely forgot. Adding... \$\endgroup\$
    – Cyoce
    Commented Jan 26, 2016 at 4:46
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ There were already some similar answers but uses ES6. \$\endgroup\$
    – jimmy23013
    Commented Jan 26, 2016 at 22:42
1
\$\begingroup\$

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

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

Lua, 47 bytes

function f(n)return(n<1 and 1 or n*f(n-1))end
\$\endgroup\$
1
\$\begingroup\$

PARI/GP, 16 bytes

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

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

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

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
\$\endgroup\$
1 2 3
4
5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.