Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Create the shortest function that finds the factorial of a natural number.

The factorial is found by multiplying a number by each of the digits that lead up to it.

5! = 5 * 4 * 3 * 2 * 1 = 120

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 (special case)
  • Completes in under a minute

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

share|improve this question
3  
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
    
Completes under a minute for factorials under 125? –  SHiNKiROU Feb 6 '11 at 23:08
3  
@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
1  
Looks like an exact duplicate of stackoverflow.com/questions/237496/code-golf-factorials which has a 2-char winner. –  ugoren Jan 13 '12 at 7:04
1  
@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 at 3:18
show 3 more comments

66 Answers

up vote 37 down vote accepted

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.

share|improve this answer
5  
Interesting, the seems to be a bug in the spoiler markdown when you use code in a spoiler... Anyone cares to mention this on Meta? –  Ivo Flipse Feb 7 '11 at 11:55
1  
+1 Well played! –  Eelvex Feb 9 '11 at 21:19
add comment

Haskell, 17

f n=product[1..n]
share|improve this answer
    
I like Haskell very much. Such mathematical tasks are usually extremely short in it. –  FUZxxl Feb 6 '11 at 17:42
2  
I don't know Haskell... But Will this calculate factorial for 0 –  The King Feb 7 '11 at 12:11
7  
@The King: yes it will. [1..0] ==> [] and product [] ==> 1 –  J B Feb 7 '11 at 12:12
1  
I would argue this uses the "built-in library" that the problem prohibits. Still, the other method f 0=1;f n=n*f$n-1 is 17 characters as well. –  eternalmatt Jul 26 '11 at 1:20
1  
@eternalmatt: that part of the restrictions is underspecified to me. Both product and, say, (*) or (-) "can calculate the factorial", and they're all defined through the Prelude. Why would one be cool and not the other? –  J B Jul 27 '11 at 9:28
show 2 more comments

J (12)

A standard definition in J:

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

Less than 1sec for 125!

Eg:

 f 0
 1
 f 5
 120
  f 125x
 1882677176888926099743767702491600857595403
 6487149242588759823150835315633161359886688
 2932889495923133646405445930057740630161919
 3413805978188834575585470555243263755650071
 31770880000000000000000000000000000000
share|improve this answer
    
why not just */>:i. ? –  Andbdrew Aug 21 '11 at 11:26
    
Because OP asks for a function and the best we can do in J is to define a verb. –  Eelvex Aug 23 '11 at 12:16
add comment

Perl 6: 13 chars

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

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

share|improve this answer
    
It's not allowed to not use a space after [*] anymore ("Two terms in a row" error message). –  xfix Dec 28 '13 at 19:24
add comment

Python - 27

Just simply:

f=lambda x:0**x or x*f(x-1)
share|improve this answer
5  
Good trick: 0**x. –  Alexandru Jul 11 '11 at 20:25
add comment

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
share|improve this answer
1  
+1 for symbolic golf entry! I wish I could upvote more than once. :-D –  Chris Jester-Young Feb 7 '11 at 0:56
add comment

Python - 28

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

(based off Alexandru's solution)

share|improve this answer
add comment

Matlab 15

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

>> f(0)
ans =
     1
>> f(4)
ans =
    24
>> tic,f(125),toc
ans =
  1.8827e+209
Elapsed time is 0.000380 seconds.
share|improve this answer
add comment

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
share|improve this answer
    
Ghostscript cannot handle 125!; anything beyond 34! comes out as 1.#INF. (I used stock GNU Ghostscript 9.0.7 compiled for x64 Windows.) –  Ross Presser Jan 7 at 6:17
add comment

Ruby - 30 29 characters

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

Test

f(0) -> 1
f(5) -> 120
share|improve this answer
1  
You can put the end directly after :* without a newline or semicolon. –  sepp2k Feb 6 '11 at 17:50
    
thanks, -1 char :-) –  user300 Feb 6 '11 at 17:56
1  
There's no need to pass 1 to the #inject call. (1..10).inject :* #=> 3628800 –  Dogbert Feb 7 '11 at 10:56
1  
@Dogbert, what about for f(0)? –  Nemo157 Feb 7 '11 at 19:05
2  
Shorter to use 1.9 lambda syntax: f=->n{(1..n).inject 1,:*}. Call it with f[n]. –  Michael Kohl Aug 22 '11 at 22:04
show 1 more comment

Ruby - 21 chars

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

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
share|improve this answer
add comment

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.

share|improve this answer
    
Don't you need a return statement in the JavaScript function? –  Justin Morgan Jul 12 '11 at 19:19
    
Update: Holy smoke, you don't need a return! But why not? –  Justin Morgan Jul 12 '11 at 19:43
    
It's JavaScript 1.8 (developer.mozilla.org/en/new_in_javascript_1.8). Full disclosure, it only works on Firefox! –  Casey Chu Jul 13 '11 at 3:53
1  
Nice, I didn't know about leaving out the return statement for JavaScript 1.8. Also, you can guarantee 1 instead of true for the n=0 case with the same length code: function f(n)n?n*f(--n):1 –  Briguy37 Aug 3 '11 at 21:50
1  
ES6, 17: f=n=>!n||n*f(n-1) Take that, CoffeeScript! –  minitech Dec 29 '13 at 3:03
add comment

C (39 chars)

double f(int n){return n<2?1:n*f(n-1);}
share|improve this answer
    
Nice. But can save some characters: double f(n){return!n?1:n*f(n-1);} - 33 chars. –  ugoren Jan 12 '12 at 16:38
add comment

APL (4)

×/∘⍳

Works as an anonymous function:

    ×/∘⍳ 5
120

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

f←×/∘⍳
share|improve this answer
    
I don't speak APL, what is going on here? –  Michael Stern Jan 6 at 21:11
    
@MichaelStern: makes an index vector, i.e. ⍳5 is 1 2 3 4 5. × is (obviously) multiply, / is reduce, and is function composition. So, ×/∘⍳ is a function that takes an argument x and gives the product of the numbers [1..x]. –  marinus Jan 6 at 23:09
    
Ah, the same approach as in @Yves Klett's Mathematica solution. Very nice. –  Michael Stern Jan 7 at 3:14
add comment

C#, 20 or 39

As a self-contained function definition (39 characters):

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

If you use a lambda expression which has been declared and initialized on a separate line, and you don't count that line in your character count, you can do it in 20:

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

Not counting the declaration line might bend the rules, but that line is necessary anyway if you want recursion in a C# lambda. Unless you have initialized f in an earlier statement, it will not be accessible from inside itself.

Used double because 125! is 1.88 * 10209, which is greater than long.MaxValue.

Test

public static void Main(string[] args)
{
    Func<int,double> f = null;            
    f=x=>x>1?f(x-1)*x:1;            
    Console.WriteLine(f(5));
}

http://rextester.com/BLAX80214

share|improve this answer
add comment

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-:#^_$>\:#^_$    .@
share|improve this answer
add comment

F#: 26 chars

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

let f n=Seq.fold(*)1{1..n}
share|improve this answer
add comment

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.

share|improve this answer
2  
take out the whitespace and you can get it down to 36 chars –  ratchet freak Jul 3 '11 at 13:36
add comment

Java

85 Chars

BigInteger f(int n){return n<2?BigInteger.ONE:new BigInteger(""+n).multiply(f(n-1));}
share|improve this answer
add comment

C#: 37

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

share|improve this answer
1  
This function returns 1 always. –  Alexandru Jul 4 '11 at 11:15
    
whoopsies, you're right. –  Origamiguy Jul 10 '11 at 12:38
    
int is way too small to hold 125!, which is something like 1.88e+209. –  Justin Morgan Jul 12 '11 at 19:05
add comment

Scala, 39 characters

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

Most of the characters are ensuring that BigInts are used so the requirement for values up to 125 is met.

share|improve this answer
add comment

Python 29

f=lambda x:x and x*f(x-1)or 1
share|improve this answer
add comment

js, 52

function f(m){n=1;for(i=1;i<=m;i++){n*=i;}return n;}
share|improve this answer
    
You can shorten that too function f(m){for(n=i=1;i<=m;)n*=i++;return n}. It's 6 character in less. –  HoLyVieR Feb 7 '11 at 3:57
add comment

PowerShell 42 (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
share|improve this answer
add comment

Python 35 Characters

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
share|improve this answer
2  
I posted a shorter similar solution. No need to repeat it you don't have an extra insight. –  Alexandru Feb 7 '11 at 12:33
add comment

Python - 35ch

reduce(lambda a,b:a*b,range(1,n+1))
share|improve this answer
add comment

PowerShell – 36

Naïve:

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

Test:

> 0,5,125|f
1
120
1,88267717688893E+209
share|improve this answer
add comment

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.

share|improve this answer
add comment

Sage: 19 chars

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

share|improve this answer
add comment

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!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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