Find the Factorial!

76

15

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.

Kevin Brown

Posted 2011-02-06T16:34:13.533

Reputation: 5 756

11How 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 – 2011-02-06T22:43:29.687

Completes under a minute for factorials under 125? – Ming-Tang – 2011-02-06T23:08:48.193

@SHiNKiROU, most languages should be able to accomplish that in well under a minute. – Kevin Brown – 2011-02-06T23:10:32.560

@Ami, there is nothing restricting the format of the output, just as long as it is correct. – Kevin Brown – 2011-02-06T23:11:37.207

6@SHiNKiROU, even golfscript can manage 125! less than 1/10th of a second and it's and interpreted interpreted language! – gnibbler – 2011-02-08T03:21:05.863

5@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 – 2014-01-07T03:18:06.343

4Completes in under a minute seems a very hardware-dependent requirement. Completes in under a minute on what hardware? – sergiol – 2017-08-24T18:05:55.893

4@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 – 2017-08-24T21:20:53.340

1Do you need an exact return or float? – l4m2 – 2017-12-25T13:16:55.193

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. – MilkyWay90 – 2019-05-07T02:02:10.477

1

Looks like an exact duplicate of http://stackoverflow.com/questions/237496/code-golf-factorials which has a 2-char winner.

– ugoren – 2012-01-13T07:04:31.257

Answers

68

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.

Nabb

Posted 2011-02-06T16:34:13.533

Reputation: 2 540

8Interesting, 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 – 2011-02-07T11:55:55.280

5I find it interesting how golfscript - a golfing language - allows multi-letter variable names and "punishes" you for using 1 letter with necessary whitespace – Cyoce – 2016-02-04T15:45:52.307

45

Haskell, 17

f n=product[1..n]

J B

Posted 2011-02-06T16:34:13.533

Reputation: 9 638

1I like Haskell very much. Such mathematical tasks are usually extremely short in it. – FUZxxl – 2011-02-06T17:42:41.207

FUZxxl: If it weren't for the horribly long name product ... – Joey – 2011-02-07T10:42:21.350

2I don't know Haskell... But Will this calculate factorial for 0 – The King – 2011-02-07T12:11:48.627

11@The King: yes it will. [1..0] ==> [] and product [] ==> 1 – J B – 2011-02-07T12:12:55.303

@TheKing product = foldl (*) 1, so product [] == foldl (*) 1 [], which is 1 (foldls initial value) – YoYoYonnY – 2016-02-06T15:58:36.677

@JB Might be worth adding this one too: (f 0=1 <NL> f n=n*f$n-1) – YoYoYonnY – 2016-02-06T16:02:09.670

2@YoYoYonnY: I count 17 characters as well, for less (subjective) readability. IMHO it's fine in the comments. – J B – 2016-02-08T13:32:31.617

5I 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 – 2011-07-26T01:20:24.557

5@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 – 2011-07-27T09:28:29.783

@J B: Good point. I'm sure this has been debated somewhere else. I suppose in my naive mind, I'd like to set aside (*) and (-) operators and pretend that they execute straight to hardware, but I guess that's not true. – eternalmatt – 2011-07-31T04:36:15.927

@eternalmatt your solution is actually not correct - Haskell will parse your code this way: f n=(n * f) $ (n - 1) which is incorrect – proud haskeller – 2014-09-09T04:23:15.293

44

Python - 27

Just simply:

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

Kirill

Posted 2011-02-06T16:34:13.533

Reputation: 661

What about math.factorial? It isn't a built-in, is it? – None – 2017-01-19T20:21:11.230

1@JackBates that counts as a builtin, as you didn't write the code to compute the factorial. – FlipTack – 2017-01-21T17:51:03.133

Ok thanks fot the clarification – None – 2017-01-21T18:02:35.610

2Can anyone tell me what's the trick behind 0**x? – Pavitra – 2019-08-04T05:36:12.060

1@Pavitra: 00=1, and it's the first thing that evaluates so it gets returned. For any other n, 0n=0, thus the first operand of or is falsey, such that the second operand gets evaluated. – Mega Man – 2019-08-05T18:13:38.160

Oh! I thought 0**0 is undefined mathematically which confused me. – Pavitra – 2019-08-06T16:34:45.657

25Good trick: 0**x. – Alexandru – 2011-07-11T20:25:23.220

29

APL (4)

×/∘⍳

Works as an anonymous function:

    ×/∘⍳ 5
120

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

f←×/∘⍳

marinus

Posted 2011-02-06T16:34:13.533

Reputation: 30 224

@NBZ: That didn't exist yet in 2011 when this question was written, nor in 2012 when I wrote this answer. Trains were only added in Dyalog 14.0 which came out in 2014. – marinus – 2016-01-25T18:38:15.470

I don't speak APL, what is going on here? – Michael Stern – 2014-01-06T21:11:29.810

@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 – 2014-01-06T23:09:42.570

Ah, the same approach as in @Yves Klett's Mathematica solution. Very nice. – Michael Stern – 2014-01-07T03:14:34.550

19

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

Eelvex

Posted 2011-02-06T16:34:13.533

Reputation: 5 204

in the last one, f 125x what does the x do? Is it a special kind of number? – Cyoce – 2016-01-21T07:11:57.723

@Cyoce, yes, it's extended precision integer.

– Eelvex – 2016-01-21T19:23:26.663

What about f=:[:*/1+i. which saves one byte? – Leaky Nun – 2016-06-24T08:52:09.827

why not just */>:i. ? – Andbdrew – 2011-08-21T11:26:25.733

Because OP asks for a function and the best we can do in J is to define a verb. – Eelvex – 2011-08-23T12:16:19.870

2There's no reason it can't be an anonymous function right? Like ([:*/1+i.) for 10 points, or even 8 as the parentheses are only needed for calling the function, not for the definition. – jpjacobs – 2014-11-04T22:05:23.207

17

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

gnibbler

Posted 2011-02-06T16:34:13.533

Reputation: 14 170

1+1 for symbolic golf entry! I wish I could upvote more than once. :-D – Chris Jester-Young – 2011-02-07T00:56:59.193

@ChrisJester-Young I'll do it for you. – Cyoce – 2016-01-21T07:30:59.773

13

Perl 6: 13 chars

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

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

Ming-Tang

Posted 2011-02-06T16:34:13.533

Reputation: 5 383

2It's not allowed to not use a space after [*] anymore ("Two terms in a row" error message). – Konrad Borowski – 2013-12-28T19:24:21.907

You don't need to set a variable, a bare code block is an acceptable answer as it implicitly forms a function. Also does this still work for 0? – Phil H – 2018-04-28T07:24:45.447

11

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!

flawr

Posted 2011-02-06T16:34:13.533

Reputation: 40 560

11​​​​​​​​​:O​​​​ – Andras Deak – 2016-01-25T12:14:07.827

I was going to post exactly this :-) You may want to modify the link to include the code and an example input – Luis Mendo – 2016-01-31T04:56:39.743

As you command, my lord. – flawr – 2016-01-31T10:43:10.693

4@AndrasDeak, No, that would output all numbers from 1 to i... – YoYoYonnY – 2016-02-06T16:09:47.033

10

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.

Jonas

Posted 2011-02-06T16:34:13.533

Reputation: 381

10

Python, 28 bytes

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

(based off Alexandru's solution)

gmanuell

Posted 2011-02-06T16:34:13.533

Reputation: 101

8

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

Wile E. Coyote

Posted 2011-02-06T16:34:13.533

Reputation: 943

8

Java, 85 Chars

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

st0le

Posted 2011-02-06T16:34:13.533

Reputation: 2 002

1This misses the imports: import java.math.*; (so, +19 bytes). – Olivier Grégoire – 2017-12-24T10:48:09.403

Fair point. ............ – st0le – 2017-12-29T19:36:01.010

7

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.

Casey Chu

Posted 2011-02-06T16:34:13.533

Reputation: 1 661

10ES6, 17: f=n=>!n||n*f(n-1) Take that, CoffeeScript! – Ry- – 2013-12-29T03:03:17.857

Don't you need a return statement in the JavaScript function? – Justin Morgan – 2011-07-12T19:19:33.260

Update: Holy smoke, you don't need a return! But why not? – Justin Morgan – 2011-07-12T19:43:59.230

It's JavaScript 1.8 (https://developer.mozilla.org/en/new_in_javascript_1.8). Full disclosure, it only works on Firefox!

– Casey Chu – 2011-07-13T03:53:28.333

1Nice, 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 – 2011-08-03T21:50:12.687

7

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}

cfern

Posted 2011-02-06T16:34:13.533

Reputation: 311

7

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

KirarinSnow

Posted 2011-02-06T16:34:13.533

Reputation: 801

1Ghostscript 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 – 2014-01-07T06:17:43.453

6

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!

Kroppeb

Posted 2011-02-06T16:34:13.533

Reputation: 1 558

1This works for 6 bytes. Taking input as a singleton is allowed by default. – ovs – 2018-08-22T17:58:03.263

@ovs thanks. But using ; instead of , allows for just a regular numerical input. -1byte anyway – Kroppeb – 2018-08-22T18:12:08.560

6

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/

Justin Morgan

Posted 2011-02-06T16:34:13.533

Reputation: 556

6

Ruby - 30 29 characters

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

Test

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

Arnaud Le Blanc

Posted 2011-02-06T16:34:13.533

Reputation: 2 286

1You can put the end directly after :* without a newline or semicolon. – sepp2k – 2011-02-06T17:50:30.320

1There's no need to pass 1 to the #inject call. (1..10).inject :* #=> 3628800 – Wile E. Coyote – 2011-02-07T10:56:30.790

1@Dogbert, what about for f(0)? – Nemo157 – 2011-02-07T19:05:11.510

@Nemo157, ah! forgot about that. – Wile E. Coyote – 2011-02-08T13:38:23.717

4Shorter to use 1.9 lambda syntax: f=->n{(1..n).inject 1,:*}. Call it with f[n]. – Michael Kohl – 2011-08-22T22:04:02.183

5

C (39 chars)

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

migf1

Posted 2011-02-06T16:34:13.533

Reputation: 59

2f(125) will overflow – jkabrg – 2015-10-14T07:12:53.783

3Nice. But can save some characters: double f(n){return!n?1:n*f(n-1);} - 33 chars. – ugoren – 2012-01-12T16:38:57.623

4

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!

Alevya

Posted 2011-02-06T16:34:13.533

Reputation: 101

4

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.

Gareth

Posted 2011-02-06T16:34:13.533

Reputation: 11 678

Some shorter options: (x:Int)=>(BigInt(1)to x).product def f(x:Int)=(BigInt(1)to x).product def f(x:BigInt)=(x.to(1,-1)).product def f(x:BigInt)=(-x to-1).product.abs – LRLucena – 2016-06-07T14:32:08.373

4

Javascript, ES6 17

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

ES6:

  • Arrow function

Afonso Matos

Posted 2011-02-06T16:34:13.533

Reputation: 312

ES6 is younger than this challenge if I'm remembering correctly and therefore not eligible. – lirtosiast – 2015-06-22T19:44:24.057

There is smth strange with conditional operator. Why there are two colons? – Qwertiy – 2015-06-25T15:43:41.010

@Qwertiy You're right, that was a typo, thanks. – Afonso Matos – 2015-06-25T18:21:10.787

4

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

Ty Auvil

Posted 2011-02-06T16:34:13.533

Reputation: 473

1This is way old now, but... Can save 1 more character by reversing the if/else: filter f($x){if($x){$x*(f($x-1))}else{1}}. And it can be reduced further to 36 characters if it's called via pipeline since it's a filter (e.g. 125|f): filter f{if($_){$_*($_-1|f)}else{1}} – Andrew – 2015-10-14T18:31:45.163

4

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.

Jonathan M Davis

Posted 2011-02-06T16:34:13.533

Reputation: 705

@Cyoce Can you explain? – YoYoYonnY – 2016-02-06T16:08:25.320

Welcome to the site, @user272735. Note that we don't edit people's solutions in order to make improvements here. Instead we leave comments suggesting those improvements, as ratchet freak did above. – Shaggy – 2019-07-29T08:29:42.320

3take out the whitespace and you can get it down to 36 chars – ratchet freak – 2011-07-03T13:36:53.347

4

PowerShell – 36

Naïve:

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

Test:

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

Joey

Posted 2011-02-06T16:34:13.533

Reputation: 12 260

4

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

kronicmage

Posted 2011-02-06T16:34:13.533

Reputation: 111

3

Befunge-93 24 22 20 bytes

Edit: Found a better way of generating the range of values

1&0>-#1:__\#0:#*_$.@

Try it online!

How it works:

1& Initialises the stack with 1 (for the special case of 0!) and the inputted factorial
  0>-#1:_ Adds the current factorial level-1 to the stack until it reaches 0
         _\# :# _ Pops another 0 and swaps the two top values of the stack. Duplicate the top value, and check whether it is 0.
         _ #0 #*_ If not, multiply the top two values of the stack and add an extra 0 so the underscore will point right. Repeat the above section.
                 $.@ If so, pop the extra 0, print the value and exit the program

Jo King

Posted 2011-02-06T16:34:13.533

Reputation: 38 234

3

Jelly, 2 bytes

RP

Try it online!

Alternatively, a builtin answer is one byte:

!

Try it online!

JHTBot

Posted 2011-02-06T16:34:13.533

Reputation: 31

3

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

Kyle Kanos

Posted 2011-02-06T16:34:13.533

Reputation: 4 270

You don't need a lot of this. K has currying, so the entire answer becomes */1.+!: 6 bytes. – kirbyfan64sos – 2015-06-25T14:43:59.390

@kirbyfan64sos: True & I'll edit it in. I think when I wrote this ~18 months ago, I was still stuck on everything must be callable (i.e., function). – Kyle Kanos – 2015-06-25T15:00:02.157

3

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.

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

enter image description here

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 :

AheuiChem image translated

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.

LegenDUST

Posted 2011-02-06T16:34:13.533

Reputation: 799

3

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!

Andbdrew

Posted 2011-02-06T16:34:13.533

Reputation: 221

3

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

KeksArmee

Posted 2011-02-06T16:34:13.533

Reputation: 131

Still impressive. – timmyRS – 2016-02-05T11:05:10.463

Take a look at https://esolangs.org/wiki/CompressedFuck. But code-golf is more about competing with other programs in the same language than it is about competing with the rest, and 125 characters for brainfuck is pretty impressive :)

– YoYoYonnY – 2016-02-06T16:15:30.877

@YoYoYonnY thanks, I updated the answer – KeksArmee – 2016-02-08T12:40:48.820

3

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-:#^_$>\:#^_$    .@

Nemo157

Posted 2011-02-06T16:34:13.533

Reputation: 1 891

I know this is pretty old, but I think this is somewhat shorter and quicker : &:!#@_>:# 1# -# :# _$>\# :#* _$.@ (where & should be replaced by the input). It's 32 chars/bytes – FliiFe – 2016-04-07T11:08:13.907

3

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

fR0DDY

Posted 2011-02-06T16:34:13.533

Reputation: 4 337

3I posted a shorter similar solution. No need to repeat it you don't have an extra insight. – Alexandru – 2011-02-07T12:33:11.447

@Alexandru if he wrote this without referencing your answer, I don't see why he shouldn't be allowed to post it just because it's longer. All Runners in a race get to post their score regardless of being first or last. – akozi – 2019-02-20T14:49:52.993

3

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

Kaslai

Posted 2011-02-06T16:34:13.533

Reputation: 641

+1 for the GCC "feature". I think GCC even allows a block return value (Can remember doing something like this) 0 == ({printf("Hello, world!"); 0;}); – YoYoYonnY – 2016-02-06T16:11:45.767

2

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
;

Titus

Posted 2011-02-06T16:34:13.533

Reputation: 13 814

for($p=1;$i++<$argn;)$p*=$i;echo$p; is shorter and <?=array_product($argn?range(1,$argn):[]); is a more interesting way – Jörg Hülsermann – 2017-07-09T00:41:56.087

2

Brainfuck, 56 bytes

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

Like the other Brainfuck answers, this assumes the IO directly inputs and outputs the number in/from the cell and the interpreter has infinite cells and infinite cell size. Add a byte if you want to avoid negative cells. Add another byte if you want to do it in place.

Note: In CompressedFuck, this is only ~21 bytes.

Jo King

Posted 2011-02-06T16:34:13.533

Reputation: 38 234

2

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!

user202729

Posted 2011-02-06T16:34:13.533

Reputation: 14 620

1

It's interesting that you don't always end up on the same stack at the end. Here's my own 52 byte answer if anyone else is interested.

– Jo King – 2018-05-22T06:26:01.733

2

Mathematica, 17

f = Times@@Range@#&

works more or less instantaneously for f[125].

Yves Klett

Posted 2011-02-06T16:34:13.533

Reputation: 251

1##& is 1 byte shorter than Times – LLlAMnYP – 2017-01-19T10:01:47.127

2

Ruby, 35 characters,

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

Test:

f(5)

=> 120

ooransoy

Posted 2011-02-06T16:34:13.533

Reputation: 163

2

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

user85052

Posted 2011-02-06T16:34:13.533

Reputation:

Nicely golfed, I gave my own shot at this but was only able to get 18 bytes, +1

– EdgyNerd – 2019-08-10T11:38:14.447

I'm getting an error running that code on TIO. – pppery – 2019-09-25T20:38:57.290

Run this in an old version. (Works for most of my Keg answers) – None – 2019-09-25T22:42:37.413

2

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

Glen O

Posted 2011-02-06T16:34:13.533

Reputation: 2 548

And it works fast enough even for ridiculously high n. For n=100,000 my old i5-2410 laptop needs only 10.3 seconds. Displaying the 456,574 digits of the result is kind of a problem, though ;)

At first I didn’t see that there already was a Julia solution. I would have almost made a double post. – M L – 2015-06-28T07:44:26.333

2

Bash+coreutils, 21 bytes

seq $1|paste -sd\*|bc

Digital Trauma

Posted 2011-02-06T16:34:13.533

Reputation: 64 644

2

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

boothby

Posted 2011-02-06T16:34:13.533

Reputation: 9 038

2

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.

Joey

Posted 2011-02-06T16:34:13.533

Reputation: 12 260

2

C#: 37

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

Origamiguy

Posted 2011-02-06T16:34:13.533

Reputation: 129

2This function returns 1 always. – Alexandru – 2011-07-04T11:15:41.327

whoopsies, you're right. – Origamiguy – 2011-07-10T12:38:07.400

3int is way too small to hold 125!, which is something like 1.88e+209. – Justin Morgan – 2011-07-12T19:05:14.647

2

Pico, 23

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

but Pico max out at 12:

>f(12)
479001600

Dan D.

Posted 2011-02-06T16:34:13.533

Reputation: 141

Does it work with 125? – user unknown – 2012-01-11T02:45:06.683

1@userunknown No, it doesn't as Pico's number type has the same limits as C's int. and fixing it so that it could would require implementing big integer multiplication and that would require at least 500-4000 characters. – Dan D. – 2012-01-11T09:55:04.753

2

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

Penguino

Posted 2011-02-06T16:34:13.533

Reputation: 231

what about removing the space between define and (! n) – jkabrg – 2015-10-13T21:49:11.520

Thanks NaN - can actually remove a lot of spaces so 47 down to 40. – Penguino – 2015-10-13T22:12:06.060

Doesn't work for me (the lambda one) - ! is undefined (running in DrRacket 6.4) – kronicmage – 2016-06-09T13:30:53.127

2

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)

lambruscoAcido

Posted 2011-02-06T16:34:13.533

Reputation: 401

1Only the last will work entirely (i.e. give 1 for n=0). A shorter solution would be : ifelse((n=scan())>0,prod(1:n),1), with 32 bytes. – Frédéric – 2016-08-26T16:11:06.597

@Frédéric or better yet "if"((n=scan())>0,prod(1:n),1) for 30 bytes. – Giuseppe – 2017-08-24T17:34:19.113

1@Giuseppe 0^(n=scan())+prod(1:n) is 22 bytes. – Robin Ryder – 2019-10-31T07:33:13.383

2

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

kaine

Posted 2011-02-06T16:34:13.533

Reputation: 536

Can you remove the -? It's throwing off the leaderboard snippet, thinks you're at negative 9 bytes. – Pavel – 2017-01-19T02:10:20.647

ri,1f+:* is even shorter – kaine – 2014-11-04T22:01:01.583

2

Ruby, 22 bytes

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

Johnson

Posted 2011-02-06T16:34:13.533

Reputation: 49

n.downto(1).inject(1,:*) – histocrat – 2015-07-24T17:12:13.063

Or in fact (1..n).inject 1,:* seems to work fine. – histocrat – 2015-07-24T17:14:07.243

Unfortunately, this doesn't work for 0, so you probably have to add a ternary operator. – Martin Ender – 2014-11-29T20:05:38.383

2

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.

mbomb007

Posted 2011-02-06T16:34:13.533

Reputation: 21 944

This is very similar to the Python answer on the first page, and doesn't really add anything. – lirtosiast – 2015-06-22T14:51:37.017

Firstly, there are many Python answers. Secondly, which answers are on which page is dependent on how you sort the answers. Thirdly, even if my answer doesn't add anything super cool or unique, it's still different enough for me to post it as my own. Because it IS my own. I created it without reading the other answers first. – mbomb007 – 2015-06-22T18:32:37.457

1There are five Python answers; two of them are exactly yours except that the authors used and/or rather than ternary or forgot to use lambda. If I had this solution, I would post it as an improvement comment on those answers due to similarity, or not post if there is no improvement. – lirtosiast – 2015-06-22T18:46:08.137

2Using and/or instead of ternary is pretty different in Python for this challenge. Your feedback is appreciated, but I'm not removing my answer. This answer was posted 5 months ago and was fine. – mbomb007 – 2015-06-22T18:51:31.753

2

Golfscript, 10 chars:

~,{)}%{*}*

Jake Summers

Posted 2011-02-06T16:34:13.533

Reputation: 21

2

Haskell, 20

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

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

Craig Roy

Posted 2011-02-06T16:34:13.533

Reputation: 790

product is probably shorter – Mega Man – 2019-08-05T18:15:07.277

2

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

Kametrixom

Posted 2011-02-06T16:34:13.533

Reputation: 426

Why is it var f:Double->Double? Isn't that declaring the type twice? var seems to declare it to be of "variable" type, whereas Double->Double seems to declare it to be a function that accepts a double and returns a double. If this is not the case, can I get an explanation of the type signature for someone who doesn't know swift? – Cyoce – 2016-02-05T06:21:19.310

@Cyoce If I was using let instead, the compiler would complain because I'm using the function itself in its definition without it being declared beforehand. By using var we can trick the compiler into thinking that f is declared already. – Kametrixom – 2016-02-05T13:30:42.640

ok, thanks for the clarification – Cyoce – 2016-02-05T15:56:24.743

2

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.

Anandaraj

Posted 2011-02-06T16:34:13.533

Reputation: 51

You don't need parens around the argument. f=n=>… is fine. – Cyoce – 2016-01-27T03:34:53.053

2

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

Conor O'Brien

Posted 2011-02-06T16:34:13.533

Reputation: 36 228

2

Python, 29 bytes

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

Alexandru

Posted 2011-02-06T16:34:13.533

Reputation: 5 485

2

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.

mroman

Posted 2011-02-06T16:34:13.533

Reputation: 1 382

Does this account for 0!=1? – AdmBorkBork – 2015-11-23T20:16:40.280

1Yes, because pd (Product) is defined to be 1 for empty lists. – mroman – 2015-11-24T09:37:33.530

2

JavaScript, 52 bytes

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

www0z0k

Posted 2011-02-06T16:34:13.533

Reputation: 200

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 – 2011-02-07T03:57:01.773

2

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

Jacob Misirian

Posted 2011-02-06T16:34:13.533

Reputation: 737

2

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!

Cyoce

Posted 2011-02-06T16:34:13.533

Reputation: 2 690

add permalinks. o_o – Conor O'Brien – 2016-01-21T04:13:18.747

@CᴏɴᴏʀO'Bʀɪᴇɴ as a matter of fact I am working on non-essentials such as permalinks and speed sliders now. :) – Cyoce – 2016-01-21T04:21:19.713

@CᴏɴᴏʀO'Bʀɪᴇɴ done. – Cyoce – 2016-01-21T05:11:25.833

2

Python - 33

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

mxdsp

Posted 2011-02-06T16:34:13.533

Reputation: 169

We already have this shorter answer using the same approach.

– lirtosiast – 2016-01-24T23:25:31.940

2

K, 9 bytes

f:*/1f+!:

k) f 125 
1.882677e+209

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

Simon Major

Posted 2011-02-06T16:34:13.533

Reputation: 401

Can you add a link to the language? – Mego – 2016-01-25T14:48:25.993

@Mego - it's https://en.wikipedia.org/wiki/K_(programming_language) I've just realised this is equivalent to Kona...

– Simon Major – 2016-01-25T14:59:51.737

2

05AB1E, 4 bytes (non-competing)

Since the language postdates the challenge, this is non-competing

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.

Adnan

Posted 2011-02-06T16:34:13.533

Reputation: 41 965

Why does the list in the range [1,N] for N=0 becomes [0].. I did know taking the product of [] becomes 1. Both seem to be the ideal situation for the 0 edge-case here.. xD – Kevin Cruijssen – 2018-08-09T14:04:55.223

1ݦP is one byte shorter. – Grimmy – 2019-05-29T13:28:58.953

2

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.

FliiFe

Posted 2011-02-06T16:34:13.533

Reputation: 543

L*F+1Sb is a bit shorter. – FryAmTheEggman – 2016-04-09T19:08:25.697

@FryAmTheEggman What kind of sorcery is this ? – FliiFe – 2016-04-09T19:38:47.493

F is fold, basically a reduce over the list, it expands pretty much into what you did, but without the start at 1 thing. So I manually add a 1 to the list Sb creates, which of course won't change the product. – FryAmTheEggman – 2016-04-09T19:40:36.763

@FryAmTheEggman I still have a lot to learn... – FliiFe – 2016-04-09T20:20:24.977

2

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

user8397947

Posted 2011-02-06T16:34:13.533

Reputation: 1 242

Hi, your solution does not handle the input value '0'; you should modify the code as follows: (defun a(b)(if(= b 0)1(*(a(- b 1))b))). – PieCot – 2016-06-06T21:47:59.850

You can save a byte by using (1- b) instead of (- b 1) – djeis – 2017-04-12T16:40:13.397

1

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!

user63571

Posted 2011-02-06T16:34:13.533

Reputation:

Factorial built-ins aren't allowed, sorry. – ETHproductions – 2017-01-19T20:16:00.360

Is that in the question? I must have missed it. – None – 2017-01-19T20:20:06.900

You can do RP# which gets the range and prints the product. – FlipTack – 2017-01-19T20:23:11.460

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 – 2017-01-19T20:24:05.803

I'm a bit hazy on the time Pushy was made – None – 2017-01-19T20:31:11.713

@JackBates late 2016. definitely not around 2011, when this challenge was made. – FlipTack – 2017-01-19T22:00:41.993

1

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.

FlipTack

Posted 2011-02-06T16:34:13.533

Reputation: 13 242

1

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

Martin Ender

Posted 2011-02-06T16:34:13.533

Reputation: 184 808

1

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

Sinusoid

Posted 2011-02-06T16:34:13.533

Reputation: 451

1

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

Cóemgein

Posted 2011-02-06T16:34:13.533

Reputation: 11

1

Pyth, 7 Bytes

u*GhHQ1

Try it online!

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

Kevin Halley

Posted 2011-02-06T16:34:13.533

Reputation: 235

1

Pyth, 3 bytes

*FS

Try it here.

Mr. Xcoder

Posted 2011-02-06T16:34:13.533

Reputation: 39 774

the S appears to no longer be necessary – hakr14 – 2018-09-12T18:20:33.457

1

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

streetster

Posted 2011-02-06T16:34:13.533

Reputation: 3 635

1

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

ბიმო

Posted 2011-02-06T16:34:13.533

Reputation: 15 345

1

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

FantaC

Posted 2011-02-06T16:34:13.533

Reputation: 1 425

Builtin is not allowed. – Weijun Zhou – 2018-02-22T03:16:00.870

@WeijunZhou Ah yes, I will update, thank you – FantaC – 2018-02-22T14:55:11.293

1@Weijun Zhou and downvoters, please retract, I have taken out the builtin – FantaC – 2018-02-22T15:01:25.783

1

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

Shoe

Posted 2011-02-06T16:34:13.533

Reputation: 657

1

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.

Mark Plotnick

Posted 2011-02-06T16:34:13.533

Reputation: 1 231

⎕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². – Adám – 2016-01-25T14:35:31.690

1

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.

Martijn Courteaux

Posted 2011-02-06T16:34:13.533

Reputation: 759

1

PHP, 41

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

donutdan4114

Posted 2011-02-06T16:34:13.533

Reputation: 259

1

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!

Alion

Posted 2011-02-06T16:34:13.533

Reputation: 965

1

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  :
<  *

Jo King

Posted 2011-02-06T16:34:13.533

Reputation: 38 234

You beat me to this answer and probably outgolfed any attempt I might have made! Looks like the -d flag is misdocumented as -e - that should be fixed soon. – Esolanging Fruit – 2018-08-07T20:41:47.813

1

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

ბიმო

Posted 2011-02-06T16:34:13.533

Reputation: 15 345

1

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

mazzy

Posted 2011-02-06T16:34:13.533

Reputation: 4 832

1

PARI/GP, 16 bytes

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

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

Charles

Posted 2011-02-06T16:34:13.533

Reputation: 2 435

1

Muriel, 128 bytes

C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";@"B:\".$(1\";a:"+~+";C:\""+|C+C

Try it online!

This is a difficult for a number of reasons. First is Muriel itself, where the only way to do loops is to create a quine and eval it, passing a condition into the code. Next is that large numbers lose precision over time (so the output for \$125!\$ is 1.88267717688893e+209), but the program can't handle that format inside the program itself, so you can't pass large numbers to the next iteration of code. The last problem is that numbers will eventually be so large, the program just renders them as Inf, but thankfully that's far beyond \$125!\$, so we don't have to worry about that.

Explanation:

The first iteration doesn't have to be a complete quine, but can take shortcuts in constructing the actual loop.

C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";

This creates an string version of the loop. This string persists across all iterations of the loop.

@                   # Evaluate the next strings as a new program
 "B:\".$(1\";       # Initialise B as the string ".$(1"
 a:"+~              # Initialise a as the inputted number
 +"C:\""+|C         # Initialise C as the persistent string C
 +C                 # And add the executing part of the program

The resulting program with input 125 looks like (newlines added for clarity)

B:".$(1";
a:125;
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";
@%(B+");B:\""+B+"*"+$a+"\";a:"+$(a-1)+";C:\""+|C+C),(a>0)*(&B+2),a*999+&B+2

The eval then executes

@                   # Evaluate
 %(     ...     ),(a>0)*(&B+2),a*999+&B+2   # The substring
   B+");                                    # If a is 0, evaluate B
                                            # Otherwise
   B:\""+B+"*"+$a+"\";                      # Concatonate "*a" to the end of B
   a:"+$(a-1)+";                            # Decrement a
   C:\""+|C                                 # Set C to C
   +C                                       # And add the executing part of the program

Eventually, a will reach 0, and B will be evaluated. B will look like:

.                         # Print
 $(       ...         )   # The string form of
   1*125*124*123*...*1    # The factorial

Jo King

Posted 2011-02-06T16:34:13.533

Reputation: 38 234

1

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!

lolad

Posted 2011-02-06T16:34:13.533

Reputation: 754

1

MathGolf, 3 bytes

╒ε*

Try it online!

Explanation

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

maxb

Posted 2011-02-06T16:34:13.533

Reputation: 5 754

1

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)

Skidsdev

Posted 2011-02-06T16:34:13.533

Reputation: 9 656

get it on tio or GH pages pls. also 7: p;#qB1Q. alternatively, p;#>q0B1Q – ASCII-only – 2019-05-03T06:47:35.297

@ASCII-only waiting for Dennis to pull the latest version – Skidsdev – 2019-05-03T13:03:46.607

argh bad paste, was p|;B1Q1 or something – ASCII-only – 2019-05-03T13:09:15.997

1

><>, 14 bytes

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

Try it online!

Emigna

Posted 2011-02-06T16:34:13.533

Reputation: 50 798

1

Julia 1.0, 12 bytes

n->prod(1:n)

Try it online!

gggg

Posted 2011-02-06T16:34:13.533

Reputation: 1 715

1

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.

Esolanging Fruit

Posted 2011-02-06T16:34:13.533

Reputation: 13 542

1

8088 / 8087 machine code, 14 bytes

More trivial iterative solution:

 D9 E8      FLD1                    ; start with 1 
 E3 0A      JCXZ +10                ; if 0, do nothing 
 51         PUSH CX                 ; push counter onto stack 
 8B F4      MOV  SI, SP             ; use stack memory for N 
        F_LOOP: 
 89 0C      MOV  WORD PTR[SI], CX   ; N = counter 
 DE 0C      FIMUL WORD PTR[SI]      ; ST =  ST * N 
 E2 FA      LOOP F_LOOP             ; keep looping 
 59         POP  CX                 ; restore stack 

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

8088 / 8087 machine code, 28 bytes

Original recursive solution:

        FACT PROC 
50          PUSH AX                 ; push input to top of stack
D9 E8       FLD1                    ; load initial 1
E8 0112     CALL FACT_H             ; start recursion
C3          RET                     ; return to caller
        FACT_H:                     ; recursive helper
55          PUSH BP                 ; save BP
8B EC       MOV  BP, SP             ; point BP to top of stack
8B 46 04    MOV  AX, [BP+4]         ; AX = N
48          DEC  AX                 ; decrement N
7C 08       JL   DONE               ; if N = 0, end recursion
50          PUSH AX                 ; save N on stack
E8 0112     CALL FACT_H             ; recursive call
9B          FWAIT                   ; synchronize CPU and FPU
DE 4E 04    FIMUL WORD PTR[BP+4]    ; accumulate result in ST(0) * N
        DONE:
5D          POP  BP                 ; restore BP
C2 0002     RET  2                  ; remove N from stack and return
        FACT ENDP

A recursive solution (at the machine code level) using only the 8088 CPU, and the 8087 FPU to calculate the factorial sum at 80-bit double-extended precision.

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

Test output displayed using Borland Turbo Debugger 3:

n = 1:

enter image description here

n = 15:

enter image description here

n = 50:

enter image description here

n = 125:

enter image description here

Notes:

  • Calculates \${125!}\$ in an imperceptible amount of time (difficult to accurately profile in DOS)
  • Specifically targeted to 8088 CPU (even includes FWAITs) to run on an original IBM PC (with FPU installed)
  • Language is not newer than the challenge

640KB

Posted 2011-02-06T16:34:13.533

Reputation: 7 149

1

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.

user3263164

Posted 2011-02-06T16:34:13.533

Reputation: 381

1

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!

user85052

Posted 2011-02-06T16:34:13.533

Reputation:

1

@, 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

user85052

Posted 2011-02-06T16:34:13.533

Reputation:

1

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.

CCP

Posted 2011-02-06T16:34:13.533

Reputation: 632

1

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.

MT0

Posted 2011-02-06T16:34:13.533

Reputation: 3 373

@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. – Cyoce – 2016-02-05T06:51:55.143

Wow... I just looked at the similarities between my code and yours. Ours are basically the same. – Drew Christensen – 2016-06-08T19:30:51.097

But will this provide the full numeric value of 125!? – WallyWest – 2014-11-05T01:37:37.343

1

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.

Timtech

Posted 2011-02-06T16:34:13.533

Reputation: 12 038

What's wrong with For(? – Khuldraeseth na'Barya – 2017-09-09T02:01:56.120

@lirtosiast I apologize for the poor quality of the previous edit, which I fixed. – Timtech – 2017-09-09T13:33:44.547

@Scrooble Nothing, I just didn't understand TI-Basic as well in Apr '14. – Timtech – 2017-09-09T13:34:08.113

1

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.

AJMansfield

Posted 2011-02-06T16:34:13.533

Reputation: 2 758

I like this solution! – lambruscoAcido – 2014-09-09T10:45:51.157

1

Python - 74

Python without any library calls. Not the shortest but calculate factorial of 125 in a flash (< 1 sec)

def factorial(n):
 if n < 1:
  return 1
 else:
  return n * factorial(n-1)

Output of 125 factorial

188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

Ricardo A

Posted 2011-02-06T16:34:13.533

Reputation: 71

@Sieg Neither of your suggestions works. They both always output 1. – mbomb007 – 2015-01-21T20:39:05.167

@mbomb007 I goof when I'm tired. Try f=lambda n:n and f(n-1)*n or 1 – seequ – 2015-01-21T20:46:25.060

@Sieg I came up with my own in a new answer. It has the same length as yours. f=lambda n:n*f(n-1)if n else 1 – mbomb007 – 2015-01-21T20:47:55.930

Because the shorter version in the answer did not actually run, I rolled back the answer to a previous revision.

– mbomb007 – 2018-04-27T21:48:40.260

For some reason my indentation is not getting preserved. – Ricardo A – 2014-06-06T03:59:59.367

Someone indented it for you, and then I reduced the indentation to only a single space per indent. I also added a character count. – Rainbolt – 2014-06-06T21:45:10.393

1You can save characters with def factorial(n):return 1 if n<1 else n*factorial(n-1) – Rainbolt – 2014-06-06T21:46:57.857

Also, in Python, 0 is equivalent to false when used as a condition, so you could literally say if n: instead of if n < 1: – Rainbolt – 2014-06-06T21:49:44.447

1You seem to have missed the point of the challenge, as this does not seem the least bit golfed, i.e., written such that the code has as few characters as possible. – Wrzlprmft – 2014-06-06T22:11:46.233

I wrote it so it is readable as well. Sure I could have called my function n and since python relies on indents jamming it all on one line will not work. Is the point to make it as short as possible even if it will not work? Serious question. I am new at this. – Ricardo A – 2014-06-06T22:21:57.100

@Ricardo The point is to write the shortest working program/function. – seequ – 2014-06-06T23:20:54.737

Also, this can be written in one line: f=lambda n:f(n-1)if n else 1 or even f=lambda n:n and f(n-1)or 1 – seequ – 2014-06-06T23:24:11.600

Also use @nicknamehere to answer to someone. – seequ – 2014-06-06T23:26:22.033

@TheRare Thanks. Then your way would have been the shortest since python relies on the indents. – Ricardo A – 2014-06-11T00:33:09.117

Check my answers and you won't think so anymore. – seequ – 2014-06-11T07:17:42.983

1

><>, 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 /

jpjacobs

Posted 2011-02-06T16:34:13.533

Reputation: 3 440

1

JavaScript, 41

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

or 39 if globals are okay.

Ry-

Posted 2011-02-06T16:34:13.533

Reputation: 5 283

1

Ruby: 22 characters

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

Sivan

Posted 2011-02-06T16:34:13.533

Reputation: 21

1

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

Mob

Posted 2011-02-06T16:34:13.533

Reputation: 191

2This is [tag:code-golf]. With barely any work at all, you can significantly reduce the length by removing unnecessary whitespace and using 1-letter variable names – Cyoce – 2016-02-05T06:30:30.950

Java's int is incapable of holding 125!, a requirement of the challenge. A Java program must use BigInteger or something similar to work. – None – 2017-03-15T17:22:28.267

Yes, and it can calculate the factorial for 0. Put the factorial value in the loop continuation condition. i.e 5 – Mob – 2011-08-06T11:17:20.503

Java's a pretty verbose language, so it's not great for getting the lowest character count. – Gareth – 2011-08-06T13:34:14.467

@Gareth Yeah, but Brain Fuck isn't right? – Mob – 2011-08-07T19:13:59.433

You asked why you rarely see Java solutions here - it's because Java's verbose and less likely to win at code-golf. That's not to say there are no Java solutions, or that people shouldn't post Java solutions - they're just rarer for that reason. – Gareth – 2011-08-07T20:06:41.820

You could try to transform your Javacode to Beanshell. – user unknown – 2012-01-11T02:46:59.613

1

Racket, 29

(λ(x)(apply * x(range 1 x)))

Matthew Butterick

Posted 2011-02-06T16:34:13.533

Reputation: 401

@overactor It creates an anonymous function, creates a list from 1 to the given number, and applies multiplication on all of it. – Mega Man – 2019-08-05T18:23:35.737

This doesn't work with 0

– EdgyNerd – 2019-11-26T15:57:04.103

Can you explain how this solution works? Not everyone is familiar with Racket. – overactor – 2014-09-09T10:15:46.073

1

Scala, 39

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

user unknown

Posted 2011-02-06T16:34:13.533

Reputation: 4 210

1

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.

Mr. Llama

Posted 2011-02-06T16:34:13.533

Reputation: 2 387

1

In Q (18 characters)

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

Computes in less than one millisecond.

q)\t f 125
0

sinedcm

Posted 2011-02-06T16:34:13.533

Reputation: 410

f:{prd 1f+til x} for 16. f:{prd 1f+(!)x} for 15. – streetster – 2017-09-13T07:44:28.163

1

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

blabb

Posted 2011-02-06T16:34:13.533

Reputation: 219

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 – AdmBorkBork – 2015-11-23T20:13:33.323

1Actually, we can move the |iex and skip the $b entirely -- 37 Bytes for param($a)((1..$a-join'*'),1)[!$a]|iex – AdmBorkBork – 2015-11-23T20:38:24.827

1

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.

Toby Speight

Posted 2011-02-06T16:34:13.533

Reputation: 5 058

2 bytes shorter using only dc ;) – ბიმო – 2017-11-26T00:09:05.110

1

PlatyPar, 8 bytes

c?1,_p\1

Try it online!

Explanation:

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

Cyoce

Posted 2011-02-06T16:34:13.533

Reputation: 2 690

This does not seem to handle the special 0 case. – Mama Fun Roll – 2016-01-26T04:04:19.493

@ՊՓԼՃՐՊՃՈԲՍԼ oops, I completely forgot. Adding... – Cyoce – 2016-01-26T04:46:09.937

1

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

Mama Fun Roll

Posted 2011-02-06T16:34:13.533

Reputation: 7 234

Mind explaining how this gets around Infinity? :) – ETHproductions – 2016-01-27T18:30:53.780

МĂ is math.js's bignumber function. – Mama Fun Roll – 2016-01-27T23:07:52.900

1

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.

ricdesi

Posted 2011-02-06T16:34:13.533

Reputation: 499

There were already some similar answers but uses ES6.

– jimmy23013 – 2016-01-26T22:42:44.123

1

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

ETHproductions

Posted 2011-02-06T16:34:13.533

Reputation: 47 880

This does not handle the zero case correctly (0! should return 1). – Mama Fun Roll – 2016-01-27T03:40:13.717

@ՊՓԼՃՐՊՃՈԲՍԼ Thanks, fixed now. – ETHproductions – 2016-01-27T23:21:31.173

I know this is old but, wouldn't á be enough? – Luis felipe De jesus Munoz – 2018-08-07T17:51:25.107

@LuisfelipeDejesusMunoz I think you mean l, but yes :-) – ETHproductions – 2018-08-08T15:30:45.797

1

Lua, 47 bytes

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

QuertyKeyboard

Posted 2011-02-06T16:34:13.533

Reputation: 71

1

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

timmyRS

Posted 2011-02-06T16:34:13.533

Reputation: 329

1

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}

Mama Fun Roll

Posted 2011-02-06T16:34:13.533

Reputation: 7 234

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.

RenderSettings

Posted 2011-02-06T16:34:13.533

Reputation: 620

Hoon is a beautiful mystery. – Lynn – 2016-03-01T01:10:42.253

1It'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. – RenderSettings – 2016-03-01T01:36:34.347

1

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.

Conor O'Brien

Posted 2011-02-06T16:34:13.533

Reputation: 36 228

1

Desmos, 18 bytes

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

Uses the formula for a! instead of a!

Formula

weatherman115

Posted 2011-02-06T16:34:13.533

Reputation: 605

1

Joy, 13 bytes

[1][*]primrec

30 char requirement in codegolf?

BlackCap

Posted 2011-02-06T16:34:13.533

Reputation: 3 576

@FryAmTheEggman To make a function you would actually have to write DEFINE f==[1][*]primerec.. I believe program arguments are thrown on the stack when the program starts, and that everything outside a define block is executed – BlackCap – 2016-06-08T20:12:34.643

1It'd be best if you knew for sure rather than just believing ;) Anyway, seems alright then, but you also wouldn't run in to that 30 character requirement if you gave some explanation of your code :P – FryAmTheEggman – 2016-06-08T20:16:02.580

1

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

Aaron

Posted 2011-02-06T16:34:13.533

Reputation: 3 689

If you run the bottom line to the left so that the pointer is moving left when it is transported, You remove the need for the second line. -1 byte 1v;n \n $<*}-1.!?:: – Jo King – 2017-12-20T05:41:28.663

Don’t forget you can remove the ; as well! – Jo King – 2017-12-21T12:41:11.507

1

Maple, 17 bytes

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

Usage:

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

DSkoog

Posted 2011-02-06T16:34:13.533

Reputation: 560

1

Mathematica

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

miles

Posted 2011-02-06T16:34:13.533

Reputation: 15 654

1

Fourier, 18 bytes

Non-competing: Fourier is newer than the challenge

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

Try it online!

Beta Decay

Posted 2011-02-06T16:34:13.533

Reputation: 21 478

1

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

TuxCrafting

Posted 2011-02-06T16:34:13.533

Reputation: 4 547

0

Tcl, 41 37 35 bytes

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

Try it online!

sergiol

Posted 2011-02-06T16:34:13.533

Reputation: 3 055

0

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

markasoftware

Posted 2011-02-06T16:34:13.533

Reputation: 346

0

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

officialaimm

Posted 2011-02-06T16:34:13.533

Reputation: 2 739

0

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

RosLuP

Posted 2011-02-06T16:34:13.533

Reputation: 3 036

0

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)

Bolce Bussiere

Posted 2011-02-06T16:34:13.533

Reputation: 970

Thought I'd let you know I made a much shorter answer, almost halving your byte count

– Jo King – 2017-11-24T09:51:59.587

0

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

RuteNL

Posted 2011-02-06T16:34:13.533

Reputation: 71

0

4, 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)

Uriel

Posted 2011-02-06T16:34:13.533

Reputation: 11 708

0

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

Olivier Grégoire

Posted 2011-02-06T16:34:13.533

Reputation: 10 647

1You can save 5 bytes by using Java 9's var and removing the r=null initialisation: n->{var r=java.math.BigInteger.ONE;for(;n>0;)r=r.multiply(r.valueOf(n--));return r;} – mgthomas99 – 2018-09-11T21:45:06.897

2@mgthomas99 Indeed! But it's Java 10's var, not Java 9's ;) and it wasn't released at the time I wrote that answer. But I have no issue switching to Java 10. – Olivier Grégoire – 2018-09-12T07:48:43.680

0

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)

reffu

Posted 2011-02-06T16:34:13.533

Reputation: 1 361

0

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]

Weijun Zhou

Posted 2011-02-06T16:34:13.533

Reputation: 3 396

0

MuPAD – 7

`*`($n)

Computes n!, no recursion.

Christopher Creutzig

Posted 2011-02-06T16:34:13.533

Reputation: 383

0

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

Bubbler

Posted 2011-02-06T16:34:13.533

Reputation: 16 616

0

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!

user10766

Posted 2011-02-06T16:34:13.533

Reputation:

2Can't you do r*=i instead of r=r*i ? – Cyoce – 2016-01-21T07:05:23.997

You may discard prompt string in input – AMK – 2014-01-07T00:23:02.877

0

Clojure, 29

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

zephjc

Posted 2011-02-06T16:34:13.533

Reputation: 21

0

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

Toby Speight

Posted 2011-02-06T16:34:13.533

Reputation: 5 058

0

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

Shaggy

Posted 2011-02-06T16:34:13.533

Reputation: 24 623

0

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.

FlipTack

Posted 2011-02-06T16:34:13.533

Reputation: 13 242

0

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)

It'sNotALie.

Posted 2011-02-06T16:34:13.533

Reputation: 209

0

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!

EvanBarbour3

Posted 2011-02-06T16:34:13.533

Reputation: 21

@JoKing changed the answer to reflect – EvanBarbour3 – 2019-02-19T12:05:21.493

0

Kotlin, 50 45 bytes

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

Thanks to @jonathan-frech

Michael

Posted 2011-02-06T16:34:13.533

Reputation: 9

1Welcome to PPCG. I think the 1->1; clause is superfluous. – Jonathan Frech – 2019-02-19T14:22:26.153

0

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.

i_saw_drones

Posted 2011-02-06T16:34:13.533

Reputation: 413

0

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

Benjamin Urquhart

Posted 2011-02-06T16:34:13.533

Reputation: 1 262

0

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

Skidsdev

Posted 2011-02-06T16:34:13.533

Reputation: 9 656

0

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.

L Rettberg

Posted 2011-02-06T16:34:13.533

Reputation: 1

1

Welcome to PPCG. There is already a Swift answer in 43 bytes. (It doesn't mean you can't post. But you may want to have a look at the existing answers in the same language first.)

– jimmy23013 – 2019-05-29T00:10:02.237

Welcome to the site! Since you are golfing in Swift you might want to check out our tips for golfing in swift question. There is one of these for most other languages as well.

– Post Rock Garf Hunter – 2019-05-29T02:29:46.030

Thanks for the prompt feedback - much appreciated! – L Rettberg – 2019-05-30T18:07:04.780

0

Pepe, 60 bytes

rrEERREeeeeeeeErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE

Try it online!

u_ndefined

Posted 2011-02-06T16:34:13.533

Reputation: 1 253

0

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.

T. Salim

Posted 2011-02-06T16:34:13.533

Reputation: 575

Hello, and welcome to Code Golf! This is a great answer, but to reduce the byte count even more, why not remove the extra spaces? – NoOneIsHere – 2019-08-03T22:23:28.753

Oh, so you only want the nonmain function. Alright. I will keep that in mind for next time. – T. Salim – 2019-08-03T22:33:49.053

You are right Jo, I fixed it. – T. Salim – 2019-08-04T00:05:55.890

Thank you A__, I removed the parentheses. – T. Salim – 2019-08-04T02:41:20.387

No, I tried to simply use long but the computer outputted 0 due to overflow, so I kept it as long double. – T. Salim – 2019-08-04T02:45:06.447

long double f(n){return!n?1:n*f(n-1);} returns the exactly same result. – None – 2019-08-04T02:47:07.803

Wow, how are you that good identifying these errors. Is there any site on codegolf that tutors people these clever shortcuts. Thanks for the advice once again. – T. Salim – 2019-08-04T02:49:24.043

There's the Tips for golfing in C page. You can also remove the (accounting spaces) part, since you're meant to count whitespace anyway.

– Jo King – 2019-08-07T05:58:18.240

0

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.

Kenneth Taylor

Posted 2011-02-06T16:34:13.533

Reputation: 183

0

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

Lyxal

Posted 2011-02-06T16:34:13.533

Reputation: 5 253

1Maybe simply increment the 0 of the stack? – None – 2019-11-24T04:10:43.337

0

W, 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

user85052

Posted 2011-02-06T16:34:13.533

Reputation:

0

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

DollarAkshay

Posted 2011-02-06T16:34:13.533

Reputation: 103

0

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.

DollarAkshay

Posted 2011-02-06T16:34:13.533

Reputation: 103

0

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

sm.abdullah

Posted 2011-02-06T16:34:13.533

Reputation: 133

0

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.

s3l1n

Posted 2011-02-06T16:34:13.533

Reputation: 11

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 – 2014-04-01T18:59:48.397

if p is bool, it would. Here I need to continue checking p with 0... – s3l1n – 2014-04-02T05:20:55.360

0

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.

Ephraim

Posted 2011-02-06T16:34:13.533

Reputation: 143

0

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}

Patrick

Posted 2011-02-06T16:34:13.533

Reputation: 101

0

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.

Aearnus

Posted 2011-02-06T16:34:13.533

Reputation: 251

0

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)

lambruscoAcido

Posted 2011-02-06T16:34:13.533

Reputation: 401

0

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!

Kasran

Posted 2011-02-06T16:34:13.533

Reputation: 681

1You don't need the 0\`` part,!will return the correct result directly. So instead your implementation should look like that0\0>-#1:$> #:#*$:!+` – FliiFe – 2016-04-07T11:14:22.020

Ah! Thank you. I'll change that now. – Kasran – 2016-04-09T17:10:21.253

0

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

Vlo

Posted 2011-02-06T16:34:13.533

Reputation: 806

0

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.

Mr. Llama

Posted 2011-02-06T16:34:13.533

Reputation: 2 387

Does not use any built-in libraries that can calculate the factorial – user unknown – 2012-01-11T02:44:24.313

3Ah, so it is cheating. – Mr. Llama – 2012-01-11T15:13:12.223

0

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.

Skyler

Posted 2011-02-06T16:34:13.533

Reputation: 897

1To 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 – 2015-10-14T17:49:18.440

0

Clojure/ClojureScript, 26 bytes

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

MattPutnam

Posted 2011-02-06T16:34:13.533

Reputation: 521

0

R 27 Bytes

function(n)prod(seq_len(n))

mnel

Posted 2011-02-06T16:34:13.533

Reputation: 826

0

Y, 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.

Conor O'Brien

Posted 2011-02-06T16:34:13.533

Reputation: 36 228

0

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

SuperJedi224

Posted 2011-02-06T16:34:13.533

Reputation: 11 342

0

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

Paul Picard

Posted 2011-02-06T16:34:13.533

Reputation: 863

26 bytes: $\=1;map$\*=$_,2..<>;print. Or 21 + 3 (flag -l61): map$\*=$_,2..<>;print. – Denis Ibaev – 2016-11-10T20:29:13.400

21 bytes: map$.*=$_,2..<>;say$. – Xcali – 2017-11-15T23:15:54.770

0

Pyke, 2 bytes (non-competing)

SB

Try it here!

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

Blue

Posted 2011-02-06T16:34:13.533

Reputation: 26 661

0

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!

Drew Christensen

Posted 2011-02-06T16:34:13.533

Reputation: 159

Yes, exactly the same as my answer from 2 years previously.

– MT0 – 2016-06-08T20:06:34.517

0

Mathcad, tbd "bytes"

enter image description here


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.

Stuart Bruff

Posted 2011-02-06T16:34:13.533

Reputation: 501

0

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.

user8397947

Posted 2011-02-06T16:34:13.533

Reputation: 1 242

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 – 2017-12-24T11:09:15.453

0

Neoscript, 31 bytes

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

TuxCrafting

Posted 2011-02-06T16:34:13.533

Reputation: 4 547

0

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)

AMK

Posted 2011-02-06T16:34:13.533

Reputation: 506

As I see no Python solution present – AMK – 2012-11-24T13:49:55.977

The first page has a Python solution with only 28 characters. – Kevin Brown – 2012-11-24T15:36:04.910

0

Logy, 47 bytes

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

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

TuxCrafting

Posted 2011-02-06T16:34:13.533

Reputation: 4 547