g | x | w | all
Bytes Lang Time Link
004Uiua250722T151000Zphidas
035Rust240812T175704Zuser9403
026Google Sheets240130T170605ZTaylor R
060Yabasic240130T170133ZTaylor R
055VBA240130T170039ZTaylor R
012J110206T182027ZEelvex
026F# .NET Core110207T113326Zcfern
028Python 2110209T164951Zgmanuell
021Ruby110207T104619ZDogbert
085Java JDK110209T090110Zst0le
041Elixir231218T201259ZCOLAMAro
003Vyxal 3231201T200505ZFmbalbue
046Kotlin231201T225342ZGinger
016ARBLE230809T014649ZATaco
004Itr230807T185422Zbsoelch
018JavaScript220104T182407ZDominik
014Julia140606T041248ZGlen O
nan230223T173750ZThe Thon
040GNU bc220605T231402Zc--
018Fourier161002T102344ZBeta Dec
002Pyke160523T114359ZBlue
003Pushy170119T201117Zuser6357
008Japt160126T224000ZETHprodu
022dc180807T105804ZToby Spe
002Chocolate220725T201503ZnaffetS
nanFig220722T213752ZSeggan
055Python 2220722T001552ZEric Xue
022RASEL220721T194644ZNakilon
017JavaScript220706T050340Zpoggersb
017Flobnar220706T005948ZBubbler
014Bash140606T225722ZDigital
015Juby220603T032326ZnaffetS
025Ruby220410T041750Zoeuf
025rusty_deque220408T142232Zbigyihsu
045Pari/GP220304T193857ZGinger
069x86 32bit machine code220228T225638Zxiver77
096RickRollLang211107T230539Zscpchick
001Dyalog APL211109T160733ZPopov
002Husk211105T124522Zscpchick
048Rust211105T145853ZMayube
020Ruby210714T162148ZAgentIva
029Python 3210616T033624ZDarkAndr
00405AB1E160126T213824ZAdnan
025Hexagony210422T203435ZUndersla
033V vim210420T161951ZAaroneou
002Vyxal210420T055147Zwasif
024Factor210326T093252Zwasif
0138088 / 8087 machine code190805T200542Z640KB
017JavaScript V8201108T220503Zaidan062
036Lua LuaJIT200821T095453Zval - di
017JavaScript Node.js200818T220532ZMaciej S
030Python 3200818T182426Zaidan062
032Flurry200813T000315ZEsolangi
019MAWP200813T075502Zlyxal
031MAWP200813T072908ZRazetime
045Python 2200316T090614ZRGS
033C gcc200318T190002ZS.S. Ann
005W191212T134950Zuser8505
008@191125T054342Zuser8505
004Keg191031T051904Zlyxal
034Wren191031T042544Zuser8505
1698Mornington Crescent190925T224624ZAlevya
016Keg190804T014620Zuser8505
013Pip190809T205717ZKenzie
037C190803T160845ZT. Salim
002MATL160125T094319Zflawr
014Julia190805T234726ZSimeon S
047Dreaderef190605T215739ZEsolangi
087Aheui esotope190529T122832ZLegenDUS
060Pepe190529T111424Zu-ndefin
053Swift 53 Characters190528T232339ZL Rettbe
012Julia 1.0190528T225046Zgggg
055NuStack190528T171245ZMayube
052Python 2190503T204231ZBenjamin
041Excel Formula190503T194327Zi_saw_dr
014><>190503T135228ZEmigna
007Clam190502T190408ZMayube
003MathGolf190308T115206Zmaxb
045Kotlin190219T141304ZMichael
010CJam190219T144757Zlolad
039PHP190219T114254ZEvanBarb
036Symbolic Python181214T230132ZFlipTack
021Powershell180914T134327Zmazzy
004Japt180912T092459ZShaggy
084Java JDK 10171224T104921ZOlivier
006Brachylog180810T182809ZKroppeb
043AsciiDots180803T220203ZAlion
014µ6180807T192509Zბიმო
022dc171126T000643Zბიმო
019Flobnar180807T063034ZJo King
052BrainFlak180522T045614Zuser2027
008Gol><>180429T232442ZBubbler
030Python150121T204132Zmbomb007
002Pyt180221T235844Zqqq
004Stax180222T034133ZWeijun Z
031Forth gforth180116T182220Zreffu
016><>160609T083910ZAaron
0374171126T211632ZUriel
002Jelly171126T185650ZJHTBot
023Javascript No body version171124T114941ZRuteNL
022Ruby141105T001424ZJohnson
035Python110207T054914ZfR0DDY
109Brainfuck171115T230031ZBolce Bu
031Axiom171113T095718Zuser5898
012Recursiva170906T095046Z0xffcour
005K oK170913T075116Zmkst
003Pyth170912T152432ZMr. Xcod
014TIBASIC140401T153037ZTimtech
007Pyth170825T194050ZKevin Ha
035Tcl170104T235814Zsergiol
015Pyth170824T170242ZCóe
038Powershell170412T152848ZSinusoid
013Alice170412T125145ZMartin E
025Python170121T175440ZFlipTack
009CJAM141104T182531Zkaine
015Bash w/Core Utils & BC170105T012826Zmarkasof
039PHP161118T105638ZTitus
003Oasis161110T184745ZTuxCraft
047Logy161003T141840ZTuxCraft
017Maple160819T184031ZDSkoog
031Neoscript160807T101336ZTuxCraft
051Java160624T015106Zuser8397
nanMathcad160610T095000ZStuart B
029Racket scheme160609T125629ZSimon Ze
3129Yup160607T030547ZConor O&
013Joy160608T195211ZBlackCap
017JavaScript ES6160607T154315ZDrew Chr
018Desmos160607T173811Zweatherm
038Common Lisp160601T210736Zuser8397
008Pyth160407T113620ZTHC
022Befunge93141104T205624ZKasran
031Perl 5160407T115306ZSake
083ForceLang160229T215822ZSuperJed
029Hoon160229T011317ZRenderSe
033Scheme140909T031649ZPenguino
010Y160219T011949ZConor O&
019DUP160214T023243ZMama Fun
047BrainFuck151013T183129ZKeksArme
nan160205T104853ZPaper
019Sage110703T075844Zboothby
016PARI/GP140107T214105ZCharles
005Detour noncompeting160121T041147ZCyoce
047Lua160130T231238ZQuertyKe
919𝔼𝕊𝕄𝕚𝕟160126T041512ZMama Fun
034JavaScript160126T215121Zricdesi
008PlatyPar160121T055100ZCyoce
013APL131228T190927ZMark Plo
009K160125T143057ZSimon Ma
052JavaScript110206T201854Zwww0z0k
042PowerShell110206T185058ZTy Auvil
029Python110206T172603ZAlexandr
nanJacobFck151123T185506ZJacob Mi
033Python160124T224113Zmxdsp
027R 27 Bytes160123T052752Zmnel
015Matlab110207T161357ZJonas
025Bash/coreutils/dc160119T183857ZToby Spe
026Clojure/ClojureScript151123T193602ZMattPutn
004Burlesque151023T085702Zmroman
012Simplex v.0.5151013T191714ZConor O&
038Python151014T174705ZSkyler
021JavaScript ES6150724T155632ZAnandara
031Powershell150707T200114Zblabb
2039C#110712T191307ZJustin M
043Swift150628T134908ZKametrix
617Javascript150622T173120ZAfonso M
006Kona140106T203904ZKyle Kan
020Haskell150624T015607ZCraig Ro
033R141104T215016ZVlo
2839Scala140909T104129Zlambrusc
nanR140909T102954Zlambrusc
087Simplefunge140909T055742ZAearnus
022Ruby140625T132246ZSivan
029Python 2.7.5140606T210541ZEphraim
030C#140401T173100Zs3l1n
046Mathematica –140401T153158ZAJMansfi
059C#140107T154742ZIt's
nan140401T143939Zsm.abdul
017JavaScript ES6 17 Characters140331T234520ZMT0
017Julia140331T130849ZCCP
037C140331T132417ZDollarAk
020C140331T130210ZDollarAk
nanRuby140112T154850Zooransoy
029Python121124T134848ZAMK
052Python 3131228T215126Zuser1076
041PHP131229T014435Zdonutdan
016Golfscript —131229T010915ZMartijn
029Clojure131229T000606Zzephjc
017Mathematica131228T220119ZYves Kle
035C++11131228T165804Zsh03
007MuPAD –131227T102606ZChristop
nan121204T231526Zmiles
004APL121204T215949Zmarinus
036F# based on cfern's110821T205117ZPatrick
023In C 23 Characters120805T040132ZKaslai
039Scala110806T141930ZGareth
018In Q120307T160050Zsinedcm
019Ruby120111T152349ZMr. Llam
039Scala120111T024312Zuser unk
010Golfscript120110T205501ZJake Sum
023Pico110821T100234ZDan D.
006J110809T015909ZAndbdrew
nan110806T111523ZMob
022><>110713T120925Zjpjacobs
041JavaScript110713T144016ZRy-
039C110711T214316Zmigf1
027Python110711T115313ZKirill
037C#110703T160602ZOrigamig
034PowerShell110703T110614ZJoey
036PowerShell –110207T103517ZJoey
025JavaScript110703T090604ZCasey Ch
045D 45 Characters110207T004702ZJonathan
013Golfscript110206T205841Zgnibbler
026PostScript110207T163501ZKirarinS
013Perl 6110206T230501ZMing-Tan
012Golfscript110206T225234ZNabb
040Befunge 2x20 =110206T203209ZNemo157
029Ruby110206T171202ZArnaud L
017Haskell110206T170331ZJ B

Uiua, 5 4 bytes

/×+1⇡

Very similar to the APL answer. Makes a range from [0, n] then adds 1 to every element before multiplying all the elements together.

pad

Edit: There's a shorter and more idiomatic way to do this:

/×⇡₁

pad

Rust, 35 bytes

fn f(n:u32)->u32{(1..=n).product()}

Attempt This Online!

Google Sheets, 26 Bytes

Anonymous worksheet function that takes input, \$n\$, from cell [A1] and outputs \$n!\$ to the calling cell.

=Product(Sequence(Max(A1,1

Excel Version, 29 Bytes

Listed separately as Excel throws an error for unpaired parens.

=PRODUCT(SEQUENCE(MAX(A1,1)))

Yabasic, 60 bytes

Port of VBA answer.

Sub f(n)
If n Then Return n*f(n-1)Else Return 1EndIf
End Sub

Try it online!

VBA, 55 Bytes

Subroutine that takes input \$n\$ and outputs \$n!\$

Function f(n)
If n Then f=n*f(n-1)Else f=1
End Function

J, 12 bytes

A standard definition in J:

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

Try it online!

Less than 1sec for 125!

Eg:

 f 0
 1
 f 5
 120
  f 125x
 1882677176888926099743767702491600857595403
 6487149242588759823150835315633161359886688
 2932889495923133646405445930057740630161919
 3413805978188834575585470555243263755650071
 31770880000000000000000000000000000000

F# (.NET Core), 26 bytes

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

let f n=Seq.fold(*)1{1..n}

Try it online!

Python 2, 28 bytes

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

Try it online!

(based off Alexandru's solution)

Ruby, 21 bytes

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

Try it online!

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

Java (JDK), 85 bytes

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

Try it online!

Elixir, 41 Characters

I didn't see any Elixir implementation, so I gave it a try

f=&(for y<-0..&1,y>0,do: y)|>Enum.product

Generate an array from an array comprehension from 0 to X, while filtering on number strictly greater than 0, and pipe it to Enum.product

Enum.product([]) returns 1, so it handle the case where our list empty when it filtered

Vyxal 3, 3 bytes

Ω}Π

Try it Online!

-2 bytes thanks to @lyxal

Explanation (outdated):

[ɾΠ|1­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌­
[      ## ‎⁡If the input is 1 or greater:
  Π    ## ‎⁢Product of
 ɾ     ## ‎⁣Range [1..n]
   |1  ## ‎⁤Else 1
💎

Created with the help of Luminespire.

Kotlin, 46 bytes

{x:Int->x.downTo(1).reduceOrNull{a,i->a*i}?:1}

Bit of a shame that we need that type hint...

Attempt This Online!

ARBLE, 16 bytes

range(1,n)/(x*y)

Reduce the range of 1-n by x*y.

Try it online!

Itr, 4 bytes

1#R*

online interpreter

Explanation

1     ; push 1
 #    ; read a number from standard input
  R*  ; reduce the range from 1 to that number with * as operator
      ; implicitly print the result of the reduction or the 1 if the range was empty

Itr, 2 bytes:

#P

Product over the range from 1 to the input. (could be considered a factorial built-in)

JavaScript, arbitrary precision, 18 bytes

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

This uses the bignum type for arbitrarily long integers.

f(125n) // 18826771768889260997437677024916008575954036487149…375565007131770880000000000000000000000000000000n

If you are content with doubles, only giving approximate results for $125!$, then you only need 17 bytes:

g=x=>x?x*g(x-1):1

We see that the double result is only accurate up to 22:

for(x=0;f(BigInt(++x))==BigInt(g(x)););x // 23

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

Edit: Note that the above was from 2014, and was for Julia 0.2. There are some tricks to squeeze the code down in modern Julia - for example, in Julia 1.8.5, !n=prod(1:n) is 12 characters, and can be used as !125, for example. Original answer kept as the "real" one for posterity.

Thunno, \$ 4 \log_{256}(96) \approx \$ 3.29 bytes

R1+P

Attempt This Online!

But, if built-ins were allowed:

F

Attempt This Online!

Explanation

R1+P  # Implicit input
R     # range(0, input)
 1+   # increment
   P  # product
      # (for an empty list
      # this gives 1)
      # Implicit output

GNU bc, 40 bytes

define f(n){for(j=1;n;)j*=n--
return j}

Try it online!

bc, 43 bytes

define f(n){
for(j=1;n;n--)j*=n
return(j)}

Try it online!

Fourier, 18 bytes

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

Try it online!

Pyke, 2 bytes

SB

Try it here!

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

Pushy, 3 bytes

RP#

Explanation:

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

Try it online!

Japt, 8 bytes

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

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

Results

$ time bash -c 'for i in 0 1 2 3 4 125 1000; do ./607.dc <<<$i | tr -dc "[0-9]"; echo; done'
1
1
2
6
24
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

real    0m0.014s
user    0m0.015s
sys     0m0.004s

Chocolate, 2 bytes

ΠỌ

Try it online!

Product of range \$[1, n]\$.

Or, using a builtin overload of product:

Chocolate, 1 byte

Π

Try it online!

Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes

ra

See the README to see how to run this

ra # Takes a num as input
 a # Range [1, n]
r  # Product

Python 2, 59 55 bytes

lambda x:reduce(lambda a,b:a*b,range(1,x+1))if x else 1

This solution uses Python 2 because reduce is built-in, in Python 3, it's part of functools. This solution is iterative, and it works for values larger than 100.

-4 by Steffan

RASEL, 22 bytes

1&\:?v:1-3\-/
1\/.@>-1

JavaScript, 17 bytes

f=n=>!n||n*f(n-1)

Flobnar, 17 bytes

>-::
>1*_
\@<^
&:

Try it online!

Individually developed as part of LYAL on 2022-07-06, and it happens to beat JoKing's 19 bytes.

How it works

\@    Start at @, facing left
&     \ pushes & (decimal input) to the call stack (call it n)
      and keep evaluating left
:
_>1   Horizontal if: if n (:) is 0, evaluate to right (1), otherwise
^

  :
  *   Multiply n (:) with the result of recursive function call
\ <   (& fails and falls through to south)
&:    called with n-1
>-
 1

Bash, 14

seq -s\* $1|bc

Try it online!

J-uby, 15 bytes

:+|:+&[1]|:/&:*

Try it online!

Ruby, 25 bytes

f=->(n){n!=0?n*f.(n-1):1}

Ruby's lambda function is a bit verbose than it should have been.

Attempt This Online!

rusty_deque, 25 bytes

1~+~1~{*~}~1~rot!2~range~

Expects a non-negative integer n on the deque, and a clean deque.

Explanation

# given an int n (n -- n!)
1~ +~  # exclusive end for range
1~     # guard for final multiplication
{*~}~  # loop body: multiply the right two numbers
1~     # index step
rot!   # ending index (n+1), rotate from the front of the deque
2~     # starting index
range~ # for i in range(2, n+1, 1)...

A version that doesn't assume a clean deque, 29 bytes:

1~+~rot~1~{*~}~1~rot!2~range~

Explanation

# given an int n (n -- n!)
1~ +~  # exclusive end for range
rot~   # save the range end at the front of the deque
1~     # guard for final multiplication
{*~}~  # loop body: multiply the right two numbers
1~     # index step
rot!   # ending index (n+1), bring the range end back
2~     # starting index
range~ # for i in range(2, n+1, 1)...

Pari/GP, 45 bytes

x=input();forstep(y=x-1,1,-1,x=x*y);print(x);

Try it online!

x86 32-bit machine code, 69 bytes

\x6a\x01\x58\x89\x03\x89\xc1\xc1\xe1\x02\x29\xcc\x89\xe7\x89\xde\xf3\xa4
\x89\xc5\x89\xd1\x49\x7e\x25\x31\xf6\x89\xf7\xf7\xdf\x8b\x3c\xb4\x11\x3c
\xb3\x19\xff\x46\x39\xee\x7c\xf1\xf7\xdf\x74\x07\x83\x04\xb3\x01\x46\x72
\xf9\x39\xf0\x0f\x4c\xc6\xeb\xd8\x8d\x24\xac\x4a\x7f\xc1\xc3

Try it online!

Unlike other machine code entries, I implemented arbitrary-precision multiplication from scratch.

The algorithm is the most basic one. For \$a × b\$, \$a\$ is added \$b\$ times with a loop. It doesn't scale well for really big numbers, but 125! is calculated within 0.3 seconds (user time) in TIO.

The function outputs an arbitrary-precision integer in base \$2 ^ {32}\$. The challenge doesn't require the function to output a string, so I can use any external method to convert the output to printable string apart from the challenge. The huge footer in TIO is the source code of mini-GMP that I copy-pasted for bignum-to-decimal-string conversion. TIO has GMP, but only for 64-bit, unfortunately.


The code is quite straightforward. Here is a pseudocode to illustrate what the assembly code is doing.

for x = y!:
  x = 1
  i from y to 1:
    z = x
    j from y - 1 to 1:
      x += z

assembly (nasm)

; input: edx, output: ebx (bignum array), eax (number of "limbs")
; custom calling convention, everything except `ebx` and `esp` gets dirty
_fac:
    push 1
    pop eax
    mov [ebx], eax
.L0:
    mov ecx, eax
    shl ecx, 2
    sub esp, ecx
    mov edi, esp
    mov esi, ebx
    rep movsb
    mov ebp, eax
    mov ecx, edx
.L1:
    dec ecx
    jle .1
    xor esi, esi
    mov edi, esi
.L2:
    neg edi
    mov edi, [esp + esi * 4]
    adc [ebx + esi * 4], edi
    sbb edi, edi
    inc esi
    cmp esi, ebp
    jl .L2
    neg edi
    jz .0
.L3:
    add dword [ebx + esi * 4], 1
    inc esi
    jc .L3
.0:
    cmp eax, esi
    cmovl eax, esi
    jmp .L1
.1:
    lea esp, [esp + ebp * 4]
    dec edx
    jg .L0
    ret

RickRoll-Lang, 164 160 96 bytes

eval too op lol

takemetourheart
ijustwannatelluhowimfeeling eval("*".join(map(str,[1,*range(1,int(input())+1)])))

Explanation:

RickRoll-Lang keywords do not need spaces between them

takemetourheart => main function declaration

ijustwannatelluhowimfeeling eval("*".join(map(str,[1,*range(1,int(input())+1)]))) => print the evaluated result of joining "*" a mapping of string to each item in a list of 1 and the range from [1, n)

=> implicit say goodbye (end block)

Try it online!

Dyalog APL, 1 char

!

! is a primitive function in Dyalog APL: in the monadic case (right argument only) gives the factorial of the right argument

https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtExQNuKAMQxjDFC6CkDP9/x8A

Husk, 2 bytes

With Product (2 bytes)

Πḣ
    implicit parameter ⁰ (last argument)
 ḣ  get the range from 1 to n
Πḣ  get the product of that list

Try it online!

With Fold (4 bytes)

F*1ḣ
       implicit parameter ⁰ (last argument)
   ḣ   get the range from 1 to n
F*1ḣ   fold left on multiplication starting with 1

Try it online!

Rust, 48 bytes

fn f(n:f64)->f64{if n==0.0{1.0}else{n*f(n-1.0)}}

Try it online!

Standard recursive solution. Unfortunately the recursion means I can't save bytes by using a closure.

Note that this solution, along with almost every non python-based answer here, uses 64-bit floats, meaning large answers such as 125! are calculated with some precision loss. This is more noticeable in rust than in, for example, JS, because JS prints the number in scientific notation, while rust prints the whole number.

Rust with num, 61/85/102 bytes

fn f(n:i64)->BigInt{if n==0{1.into()}else{(n*f(n-1)).into()}}

Try it in Rust Playground

This answer is longer, but uses the BigInt type provided by the num crate and as a result calculates with maximum precision.

+24 bytes for a total of 85 if you want to count use num::bigint::BigInt;
or
+41 bytes for a total of 102 if you want to count extern crate num;use num::bigint::BigInt;

Rust Playground can be a little unpredictable, so if you get a timeout when trying to run this, keep trying. It should work eventually.

Ruby - 20 chars

f=->n{0**n|n*f[n-1]}

Test

irb(main):009:0> f=->n{0**n|n*f[n-1]}
=> #<Proc:0x25a6d48@(irb):9 (lambda)>
irb(main):010:0> f[125]
=> 188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000

Python 3, 32 29 bytes

lambda n:n*f(n-1)if n>0else 1

Try it online! Just a simple recursive solution I made for Generalised multi-dimensional chess knight's moves.

Thanks for the -3 Maanas

05AB1E, 4 bytes

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.

Hexagony, 25 bytes

?{)"(&=}<!{\.@*$><>}=/\._

Formatted:

   ? { ) "
  ( & = } <
 ! { \ . @ *
$ > < > } = /
 \ . _ . . .
  . . . . .
   . . . .

Try it online! or Try it online differently!

V (vim), 33 bytes

S<C-r>=r<Tab>1,<C-r>"<BS>)
<C-o>:%s/\n/*/g
<C-o>C<C-r>=<C-r>"<BS><BS>

Try it online!

Explanation:

S<C-r>=r<Tab>1,<C-r>"<BS>)  # Replace N with [1, ..., N]
<C-o>:%s/\n/*/g             # Merge all lines with *
<C-o>C<C-r>=<C-r>"<BS><BS>  # Remove trailing * and evaluate.

Overflows for any N greater than 49, but would work properly otherwise.

Vyxal, 2 bytes

ɾΠ

Range of 1 to input and product

Try it!

Factor, 24 bytes

[ [1,b] 1 [ * ] reduce ]

Try it online!

Computes 125 factorial very quickly

-2 bytes thanks to @chunes

Factor, 12 bytes

[ [1,b] Π ]

Try it online!

Thanks to @chunes

8088 / 8087 machine code, 13 bytes

D9 E8       FLD1                ; start with 1 
E3 08       JCXZ DONE           ; if N = 0, return 1 
        FACT_LOOP: 
51          PUSH CX             ; push current N onto stack
8B F4       MOV  SI, SP         ; SI to top of stack for N 
DE 0C       FIMUL WORD PTR[SI]  ; ST = ST * N 
59          POP  CX             ; remove N from stack 
E2 F8       LOOP FACT_LOOP      ; decrement N, loop until N = 0
        DONE: 
C3          RET                 ; return to caller

Input \$n\$ is in CX, 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:

JavaScript (V8), 17 bytes

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

Try it online!

Lua (LuaJIT), 36 bytes

x=1 for i=1,...do x=x*i end print(x)

Try it online!

Because who needs recursion anyways?

I'm using LuaJIT instead of mainline Lua because Lua 5.3+ would make x 64-bit signed integer (and, sadly, LuaJIT implements Lua 5.1), making code fail on big values. It costs single byte to fix it:

Lua, 37 bytes

x=1. for i=1,...do x=x*i end print(x)

Try it online!

Now it's double again.

JavaScript (Node.js), 17 bytes

Recursion. Usage of arrow function declaration and OR operator that checks whether x is 0 (if not, continue multiplying).

f=x=>!x||x*f(x-1)

Try it online!

Python 3, 30 Bytes

f=lambda n:n*f(n-1)if n else 1

125! took less than 1 second to do on IDLE and TIO.

How it works: the function f returns n*f(n-1) if n is not 0 and it returns 1 otherwise, the definition of a factorial.

Try it online!

Flurry, 32 bytes

{{}{<{}(<><<>()>{})>}[(<>())()]}

This is an anonymous function that takes an argument as a Church numeral and returns a Church numeral as output.

You can test it with the interpreter as follows:

$ ./Flurry -nin -c '{{}{<{}(<><<>()>{})>}[(<>())()]}{}' 9
362880

While the function itself returns quickly for N=125, the resulting Church numeral is too large to be practically useful for any purpose, including being converted into an integer and displayed by the interpreter.

Explanation

As with my Fibonacci answer, we're iterating a function \$n\$ times and storing an additional variable using the stack. In this case, the variable on the stack is the counter, so the step function looks like this:

next = λn. n * push(1 + pop())

This admits a straightforward translation that uses function composition for multiplication and <><<>()> for the successor function:

{<{} (<> <<> ()> {})>}

The main function is responsible for setting up initial values and calling next the appropriate number of times. It looks like this:

main = λn. push(0); n (next) (1)

The Church numeral representation of zero is λab. b; in other words, a constant function that ignores its argument and returns the identity function. By coincidence, the Church numeral representation of one is λab. ab, which is itself the identity function. Thus we can rewrite it as:

main = λn. n (next) (push(0) (arbitrary value))

This can again be translated directly:

{{} {<{}(<><<>()>{})>} [(<>()) ()]}

MAWP, 19 bytes

|[!1A]%_1A[%W_1A]~:

Utilises this input/output consensus that numbers can be taken as ascii characters.

MAWP, 19 bytes

@[!1A]%_1A[%W_1A]~:

Try it!

If you want to enter normal numbers like normal people.

MAWP, 31 bytes

%@<:.>!!1A[1A~!1A~]%1A[1A~W~]%:

125! takes around 11 seconds, so it fulfills the criteria.

Try it!

Python 2, 45 bytes

lambda n:reduce(long.__mul__,range(1,n+1),1L)

Try it online! Not the shortest Python solution but I thought it would be interesting to post a solution with reduce and long.__mul__.

C (gcc), 33 bytes

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

Output:

1
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
51090942171709440000
1124000727777607680000
25852016738884978212864
620448401733239409999872
15511210043330986055303168
403291461126605650322784256
10888869450418351940239884288
304888344611713836734530715648
8841761993739700772720181510144
265252859812191032188804700045312
8222838654177922430198509928972288
263130836933693517766352317727113216
8683317618811885938715673895318323200
295232799039604119555149671006000381952
10333147966386144222209170348167175077888
371993326789901177492420297158468206329856
13763753091226343102992036262845720547033088
523022617466601037913697377988137380787257344
20397882081197441587828472941238084160318341120
815915283247897683795548521301193790359984930816
33452526613163802763987613764361857922667238129664
1405006117752879788779635797590784832178972610527232
60415263063373834074440829285578945930237590418489344
2658271574788448529134213028096241889243150262529425408
119622220865480188574992723157469373503186265858579103744
5502622159812088456668950435842974564586819473162983440384
258623241511168177673491006652997026552325199826237836492800
12413915592536072528327568319343857274511609591659416151654400
608281864034267522488601608116731623168777542102418391010639872
30414093201713375576366966406747986832057064836514787179557289984
1551118753287382189470754582685817365323346291853046617899802820608
80658175170943876845634591553351679477960544579306048386139594686464
4274883284060025484791254765342395718256495012315011061486797910441984
230843697339241379243718839060267085502544784965628964557765331531071488
12696403353658276446882823840816011312245221598828319560272916152712167424
710998587804863481025438135085696633485732409534385895375283304551881375744
40526919504877220527556156789809444757511993541235911846782577699372834750464
2350561331282878906297796280456247634956966273955390268712005058924708557225984
138683118545689864933221185143853352853533809868133429504739525869642019130834944
8320987112741391580056396102959641077457945541076708813599085350531187384917164032
507580213877224835833540161373088490724281389843871724559898414118829028410677788672
31469973260387939390320343330721249710233204778005956144519390914718240063804258910208
1982608315404440084965732774767545707658109829136018902789196017241837351744329178152960
126886932185884165437806897585122925290119029064705209778508545103477590511637067401789440
8247650592082471516735380327295020523842257210146637473076098881993433291790288339528056832
544344939077443069445496060275635856761283034568718387417404234993819829995466026946857533440
36471110918188683221214362054827498508015278133658067038296405766134083781086959639263732301824
2480035542436830547970901153987107983847555399761061789915503815309070879417337773547217359994880
171122452428141297375735434272073448876652721480628511030304905066123383956194496253690059725733888
11978571669969890269925854460558840225267029209529303278944419871214396524861374498691473966836482048
850478588567862176139364498862283450363106657876759119884137546969850291984346623845721803156845756416
61234458376886076682034243918084408426143679367126656631657903381829221022872956916891969827292894461952
4470115461512683367030518111879159855011125453675376127499372976904192242294440576507107183576895048384512
330788544151938558975078458606627397928594841525087028177611631961228972749086355889619432768006702663467008
24809140811395391401649674453868616759922516881580717884144963618612492793329521656999844718186305916810297344
1885494701666049846649767567286674986020753759697889931196791720482648043560619012598537844549685032003930423296
145183092028285837925033723190960213624220326225543510376814897182582303110787462992309948307745678711432381726720
11324281178206294606285193764734547659641544873910049469239570110699644621282776159978832493218689331409071173009408
894618213078297291394536105678124660091699861979864830895281485890971416487504167917951760559283842969422038852173824
71569457046263778832073404098641551692451427821500630228331524401978643519022131505852398484420816675798776564959674368
5797126020747365547859207609316955153302418317114924299299934140244381749043408420663995193999459259329102516576025837568
475364333701283981804950871934204857403260987909684614932289567004882674634326008655216234173410083475042065689611178344448
39455239697206569095363763848575524105091557652834963035068520647090338762195044371133838774594273621857211161281310377377792
3314240134565351991893962785187002255986138585985099085000359647021178112607661449751964466234594461331925608329126314254532608
281710411438054936145340070063731769270618697594701234453923080571636972801512907171791271651453851961008097129997800044545179648
24227095383672724277628115968482030522825707406365319023898287641277303090920578351271773357158562842391230015963508220979549569024
2107757298379526908723379823722428723253356281476796516744835439819327865545820130415624631892617112325588092315921658107822337949696
185482642257398355359015441641340379717002520724001675848028952155157918424578282117944000727442910232086550560628100855367408841392128
16507955160908452497218052643056785820348586593118454131228292379023767876373998621963681432374396360185860939835599722920061648806871040
1485715964481760688598126444658390468648504385338494631194665214503009929244428884407664620677918947601692538663274334960161140774153486336
135200152767840228116141248983464474000315190336164090023053168975093962659595589494945258181259227289565007146009064474002163016890673266688
12438414054641300055918190849808704283732243800785472203727097932000687811897290487171609691949473988773572358313712866199772466321053448142848
1156772507081640872708168771053910362702557453046286765300873130615713476227390429979366250504125810956242157790289615727775585913909863306493952
108736615665674240994816729183762001752135081532694567149618171011945851076444857687577437120278217589896360543234882091889200965381187714945122304
10329978488239052206885505130495304991006115078121225426977331552932345209983325487893772190631276157126501537780698430576453773283127019334195478528
991677934870949102715849029478410597802063033500204435194993914996262675344674144417713144475342926858025486847392744430654763018452435547907969515520
96192759682482062236598631563798937437476306361515295860273049067319419226943192827878886900710340579037421510433530649010990406523708314612471414390784
9426890448883242029410148360874034376137592466180063696357188182614769297217373775790759257383412737431326439501183709769874985637770333212700442263289856
933262154439440960911604687726529403237621654151826305939361630078862160424520003803285166480957861005701317510617187267217623578139262988057343784065695744
93326215443944102188325606108575267240944254854960571509166910400407995064242937148632694030450512898042989296944474898258737204311236641477561877016501813248
9425947759838353638138390835342801376610975723095888339920014242478768251047951733961834230251772401385381873852523273511991274827736142409989069734354272387072
961446671503512108551098468996872516993486281273776279655019164712488171916774592368567957322868226384982187894861027816146283489308561271194593264363559458963456
99029007164861753574104173353829959119840213587603550977595970143247198666981236326723820707135417324040064427202242800388622136039545500810497297411854931555516416
10299016745145621553359182054762848245165958006210981247509469384131511290543206553945828252373444680882643618952993963518745670258094979779977582459484649549641809920
1081396758240290348210869921049787686085357708169730988621187482453493212072612258663790673020750118457699980463572452092522082693661819116546316351266107589254107365376
114628056373470783195262178791869885150372134974981857049798601542754676287616326162938700437174657932394775194874661651509774290443489164051042101334162066851708352331776
12265202031961373185133888353370611130684668524854136840277622617824654987491120488233295563394527465880023230174031122970080372499095001280782895493213123617184939419631616
1324641819451828358912841223208903721969150593335392516905465643871506013804748686213541388027857383295519634150431801099139171361749124435300456711000167851248199786240671744
144385958320249281895211638114231048758962740708165300332574711789391685278558717651905972808586720726491483073402144430319927168280381361555797909879849011686559753441596407808
15882455415227421289655392351515189289144558208272049215939288190702874949438682229949505800912531174854106019567414459205248903105897894971654398555177121848553771682648345804800
1762952551090243665975210588885144142387414195100989311383803233846619844411373359108703401397152961517526948327940490533490958560703331680555091440947787242605540750086427113422848
197450685722107283218203224975563190350604098858598125302874203564961210901795886052940088784315404959246758100114554585320567376838138578357747136064291560700269291680195376450633728
22311927486598122561395742763464263293811085711458827504898079485289004131566259313948148502297697156551908058556057846875398914665071585162560040055953309730837353620093009923758096384
2543559733472186205984785013970489854470847792378977572407496727142253030323344177018786997575166305186774479690234182114834728179176544494308091621715820528124381901517757837570933260288
292509369349301414171317466983763626351066482490080838864228039834663473319338986788600397507339178163503285987117253188513945744543074764016065369127692817702167502857927244907779926786048
33931086844518965033194432062534716898733796047438137448775849025668322561295546839066546536978813348231985419477781328258303410431554030031323720045817206723636050739092232075729560101978112
3969937160808719035516914105546083316129144899609623379494025075823655775671863699734165199370837152945139637435339450080229269140755163261563772810417232690049049348643093126163025872065396736
468452584975428833021146646814567601649600858899761983789620882005863329785250305734040051053149920962518753508300395503370245666101721723083039844863345029073890156274277583663759649529785221120
55745857612076033333946596938961053806019179795001037546326945837492339367137742780510072138432293369384101420636637780506186496519649138194305750351243690774695184219682241207240231351096375771136
6689502913449123933681342530579439120523775756341546089360093784620090324126011858610763674005344861930779387322735825049576193801545269664994272835560837966773424760538449951889918907707412713570304
809429852527344001286822374367783120479258932042013350108502525209350161213688816895938003163169155685249328518343891519892014312451987782930100389629933788074784183691025963616992896186529128659288064
98750442008335975771386594694042667512406118845315870110284243810270370655301200902289870551084388902234050553564994114624253260948981065526033632124062906320002086008101445028038232030953741735287586816
12146304367025324845837253661169005205421689094860932220203889171869434996608192505473415582579316934206019475818161948117127665043471218350935019389220629267648749936761134253494071712465660221123700195328
1506141741511140361082970935625106973149134079213189040694064611290402469291784349376899830829867484515795051439621218300470678438729622083715830084690979092223507252900426925300358777584774193094861734805504
188267717688892538291710440519845543681884351351211642746915315538460412792684266823199728040717355805605164453895552619595370444449591794431421678523215389148946427029232083284552835657699349012546428480782336

Try it online!

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

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

Keg, 9 5 4 bytes

Ï⑨∑*

Try it online!

-1 byte thanks to @A̲̲

Answer History

5 Bytes

Ï_1∑*

Try it online!

This:

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!

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!

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

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.

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.

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!

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.

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.

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.

Pepe, 60 bytes

rrEERREeeeeeeeErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE

Try it online!

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.

Julia 1.0, 12 bytes

n->prod(1:n)

Try it online!

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

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

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.

><>, 14 bytes

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

Try it online!

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)

MathGolf, 3 bytes

╒ε*

Try it online!

Explanation

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

Kotlin, 50 45 bytes

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

Thanks to @jonathan-frech

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!

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!

Symbolic Python, 36 bytes

__('__=_==_'+';__*=_;_=~-_'*_)
_=+__

Try it online!

Can compute 125! with ease.

Works using an 'exec' pseudo-loop:

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

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

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

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!

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!

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

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

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

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!

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

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.

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

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]

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)

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

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)

Jelly, 2 bytes

RP

Try it online!

Alternatively, a builtin answer is one byte:

!

Try it online!

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

Ruby, 22 bytes

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

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

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)

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

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

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

Pyth, 3 bytes

*FS

Try it here.

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.

Pyth, 7 Bytes

u*GhHQ1

Try it online!

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

Tcl, 41 37 35 bytes

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

Try it online!

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

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

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

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.

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

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

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
;

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

Logy, 47 bytes

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

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

Maple, 17 bytes

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

Usage:

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

Neoscript, 31 bytes

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

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.

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.

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

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.

Joy, 13 bytes

[1][*]primrec

30 char requirement in codegolf?

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!

Desmos, 18 bytes

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

Uses the formula for a! instead of a!

Formula

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

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.

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!

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

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

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.

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

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.

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}

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

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

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

PARI/GP, 16 bytes

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

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

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!

Lua, 47 bytes

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

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

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.

PlatyPar, 8 bytes

c?1,_p\1

Try it online!

Explanation:

c?        ## if (n != 0)
  1,_p     ## product [1..n]
       \  ## else
        1  ## 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.

K, 9 bytes

f:*/1f+!:

k) f 125 
1.882677e+209

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

JavaScript, 52 bytes

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

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

Python, 29 bytes

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

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

Python - 33

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

R 27 Bytes

function(n)prod(seq_len(n))

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.

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.

Clojure/ClojureScript, 26 bytes

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

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.

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

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.

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.

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

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/

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:

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

Javascript, ES6 17

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

ES6:

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

Haskell, 20

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

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

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

Scala, 28 (39 w/ recursion)

Solution:

def f(n:Int)=(1 to n)product

Recursive solution:

def f(n:Int):Int=if(n<2)1 else n*f(n-1)

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

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.

Ruby: 22 characters

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

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.

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.

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.

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)

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

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.

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.

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.

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

Ruby, 35 characters,

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

Test:

f(5)

=> 120

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)

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!

PHP, 41

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

Golfscript — 16

{.!+,{(}%{*}*}:f

The way I handle 0! is to do this trick: .!+:

or:

{),{)}%);{*}*}:f

Here, I start of by increasing the argument by 1. But before I factor the array, I drop the last element.

Clojure, 29

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

Mathematica, 17

f = Times@@Range@#&

works more or less instantaneously for f[125].

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

MuPAD – 7

`*`($n)

Computes n!, no recursion.

Mathematica

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

APL (4)

×/∘⍳

Works as an anonymous function:

    ×/∘⍳ 5
120

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

f←×/∘⍳

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}

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

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.

In Q (18 characters)

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

Computes in less than one millisecond.

q)\t f 125
0

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.

Scala, 39

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

Golfscript, 10 chars:

~,{)}%{*}*

Pico, 23

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

but Pico max out at 12:

>f(12)
479001600

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!

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

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

JavaScript, 41

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

or 39 if globals are okay.

C (39 chars)

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

Python - 27

Just simply:

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

C#: 37

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

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.

PowerShell – 36

Naïve:

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

Test:

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

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.

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.

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

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

Perl 6: 13 chars

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

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

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.

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

Ruby - 30 29 characters

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

Test

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

Haskell, 17

f n=product[1..n]