# Find the Factorial!

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

The factorial, represented with ! is defined as such

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

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

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

Requirements:

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

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

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

## PHP, 13

Might sound like cheating, but in PHP it's just:

gmp_fact($n); Will get you 100% precision, but it won't always be fast, especially for larger numbers. • Does not use any built-in libraries that can calculate the factorial – user unknown Jan 11 '12 at 2:44 • Ah, so it is cheating. – Mr. Llama Jan 11 '12 at 15:13 ## 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}  MuPAD – 7 *($n)


Computes n!, no recursion.

# Clojure, 29

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


# 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 #includes and whitespace!

• You may discard prompt string in input – AMK Jan 7 '14 at 0:23
• Can't you do r*=i instead of r=r*i ? – Cyoce Jan 21 '16 at 7:05

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

• As I see no Python solution present – AMK Nov 24 '12 at 13:49
• The first page has a Python solution with only 28 characters. – Kevin Brown Nov 24 '12 at 15:36

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

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. – Glenn Randers-Pehrson Apr 1 '14 at 18:59
• if p is bool, it would. Here I need to continue checking p with 0... – s3l1n Apr 2 '14 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.

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


# 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. – Kevin Brown Oct 14 '15 at 17:49

# Clojure/ClojureScript, 26 bytes

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


# R 27 Bytes

function(n)prod(seq_len(n))


# Y, 10 bytes

Try it here!

jC:t:tF|*p


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.

# 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


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

• 26 bytes: $\=1;map$\*=$_,2..<>;print. Or 21 + 3 (flag -l61): map$\*=$_,2..<>;print. – Denis Ibaev Nov 10 '16 at 20:29 • 21 bytes: map$.*=$_,2..<>;say$. – Xcali Nov 15 '17 at 23:15

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

• You don't need the 0 part, ! will return the correct result directly. So instead your implementation should look like that 0\0>-#1:_$> #\:#*_$:!+ – FliiFe Apr 7 '16 at 11:14
• Ah! Thank you. I'll change that now. – Kasran Apr 9 '16 at 17:10

## Pyke, 2 bytes (non-competing)

SB


Try it here!

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


# JavaScript ES6, 19 17 bytes

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


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

## Ungolfed

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


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

## See it in Action

Check it out on JSFiddle!

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

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

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

# Java, 51 bytes

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


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

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

## Neoscript, 31 bytes

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


## Logy, 47 bytes

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


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

# Bash w/Core Utils & BC, 15 Bytes

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

seq -s* dd|bc


number to factorial for from stdin, factorial to stdout

# Pushy, 3 bytes

Non-competing as the language postdates the challenge.

RP#


Explanation:

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


Try it online!

• Factorial built-ins aren't allowed, sorry. – ETHproductions Jan 19 '17 at 20:16
• Is that in the question? I must have missed it. – user63571 Jan 19 '17 at 20:20
• You can do RP#` which gets the range and prints the product. – FlipTack Jan 19 '17 at 20:23
• Thanks for using Pushy, but as it postdates this challenge you should mark the answer as non-competing (and maybe include a TIO link) – FlipTack Jan 19 '17 at 20:24
• I'm a bit hazy on the time Pushy was made – user63571 Jan 19 '17 at 20:31