Factorial: Difference between revisions

97,311 bytes added ,  13 days ago
m
fixed incorrect placement
(→‎{{header|langur}}: added Iterative Folding example)
m (fixed incorrect placement)
 
(249 intermediate revisions by more than 100 users not shown)
Line 27:
This is an iterative solution which outputs the factorial of each number supplied on standard input.
 
<langsyntaxhighlight lang="0815">}:r: Start reader loop.
|~ Read n,
#:end: if n is 0 terminates
Line 37:
{+% Dequeue incidental 0, add to get Y into Z, output fac(n).
<:a:~$ Output a newline.
^:r:</langsyntaxhighlight>
 
{{out}}
Line 50:
=={{header|11l}}==
 
<langsyntaxhighlight lang="11l">F factorial(n)
V result = 1
L(i) 2..n
Line 57:
 
L(n) 0..5
print(n‘ ’factorial(n))</langsyntaxhighlight>
 
{{out}}
Line 71:
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<langsyntaxhighlight lang="360asm">FACTO CSECT
USING FACTO,R13
SAVEAREA B STM-SAVEAREA(R15)
Line 86:
L R15,=A(FACT)
BALR R14,R15 call fact(n)
ZAP F,0(L'R,R1) f=fact(n)
DUMP EQU *
MVC S,MASK
ED S,N
MVC WTOBUF+5(2),S+30
MVC S,MASK
ED S,F
MVC WTOBUF+9(32),S
WTO MF=(E,WTOMSG)
AP N,=P'1' n=n+1
B LOOPN
ENDLOOPN EQU *
RETURN EQU *
Line 111:
LOOP CP I,L if i>l
BH ENDLOOP then goto endloop
MP R,I r=r*i
AP I,=P'1' i=i+1
B LOOP
ENDLOOP EQU *
LA R1,R return r
Line 134:
LTORG
YREGS
END FACTO</langsyntaxhighlight>
{{out}}
<pre>FACT(29)= 8841761993739701954543616000000 </pre>
 
=={{header|68000 Assembly}}==
This implementation takes a 16-bit parameter as input and outputs a 32-bit product. It does not trap overflow from <tt>0xFFFFFFFF</tt> to 0, and treats both input and output as unsigned.
 
<syntaxhighlight lang="68000devpac">Factorial:
;input: D0.W: number you wish to get the factorial of.
;output: D0.L
CMP.W #0,D0
BEQ .isZero
CMP.W #1,D0
BEQ .isOne
MOVEM.L D4-D5,-(SP)
MOVE.W D0,D4
MOVE.W D0,D5
SUBQ.W #2,D5 ;D2 = LOOP COUNTER.
;Since DBRA stops at FFFF we can't use it as our multiplier.
;If we did, we'd always return 0!
.loop:
SUBQ.L #1,D4
MOVE.L D1,-(SP)
MOVE.L D4,D1
JSR MULU_48 ;multiplies D0.L by D1.W
EXG D0,D1 ;output is in D1 so we need to put it in D0
MOVE.L (SP)+,D1
DBRA D5,.loop
MOVEM.L (SP)+,D4-D5
RTS
.isZero:
.isOne:
MOVEQ #1,D0
RTS
MULU_48:
;"48-BIT" MULTIPLICATION.
;OUTPUTS HIGH LONG IN D0, LOW LONG IN D1
;INPUT: D0.L, D1.W = FACTORS
MOVEM.L D2-D7,-(SP)
SWAP D1
CLR.W D1
SWAP D1 ;CLEAR THE TOP WORD OF D1.
MOVE.L D1,D2
EXG D0,D1 ;D1 IS OUR BASE VALUE, WE'LL USE BIT SHIFTS TO REPEATEDLY MULTIPLY.
MOVEQ #0,D0 ;CLEAR UPPER LONG OF PRODUCT
MOVE.L D1,D3 ;BACKUP OF "D1" (WHICH USED TO BE D0)
;EXAMPLE: $40000000*$225 = ($40000000 << 9) + ($40000000 << 5) + ($40000000 << 2) + $40000000
;FACTOR OUT AS MANY POWERS OF 2 AS POSSIBLE.
MOVEQ #0,D0
LSR.L #1,D2
BCS .wasOdd ;if odd, leave D1 alone. Otherwise, clear it. This is our +1 for an odd second operand.
MOVEQ #0,D1
.wasOdd:
MOVEQ #31-1,D6 ;30 BITS TO CHECK
MOVEQ #1-1,D7 ;START AT BIT 1, MINUS 1 IS FOR DBRA CORRECTION FACTOR
.shiftloop:
LSR.L #1,D2
BCC .noShift
MOVE.W D7,-(SP)
MOVEQ #0,D4
MOVE.L D3,D5
.innershiftloop:
ANDI #%00001111,CCR ;clear extend flag
ROXL.L D5
ROXL.L D4
DBRA D7,.innershiftloop
ANDI #%00001111,CCR
ADDX.L D5,D1
ADDX.L D4,D0
MOVE.W (SP)+,D7
.noShift:
addq.l #1,d7
dbra d6,.shiftloop
MOVEM.L (SP)+,D2-D7
RTS
</syntaxhighlight>
 
{{out}}
10! = 0x375F00 or 3,628,800
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program factorial64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLargeNumber: .asciz "Number N to large. \n"
szMessNegNumber: .asciz "Number N is negative. \n"
szMessResult: .asciz "Resultat = @ \n" // message result
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x0,#-5
bl factorial
mov x0,#10
bl factorial
mov x0,#20
bl factorial
mov x0,#30
bl factorial
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
/********************************************/
/* calculation */
/********************************************/
/* x0 contains number N */
factorial:
stp x1,lr,[sp,-16]! // save registers
cmp x0,#0
blt 99f
beq 100f
cmp x0,#1
beq 100f
bl calFactorial
cmp x0,#-1 // overflow ?
beq 98f
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
b 100f
98: // display error message
ldr x0,qAdrszMessLargeNumber
bl affichageMess
b 100f
99: // display error message
ldr x0,qAdrszMessNegNumber
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
 
qAdrszMessNegNumber: .quad szMessNegNumber
qAdrszMessLargeNumber: .quad szMessLargeNumber
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* calculation */
/******************************************************************/
/* x0 contains the number N */
calFactorial:
cmp x0,1 // N = 1 ?
beq 100f // yes -> return
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save N in x20
sub x0,x0,1 // call function with N - 1
bl calFactorial
cmp x0,-1 // error overflow ?
beq 99f // yes -> return
mul x10,x20,x0 // multiply result by N
umulh x11,x20,x0 // x11 is the hi rd if <> 0 overflow
cmp x11,0
mov x11,-1 // if overflow -1 -> x0
csel x0,x10,x11,eq // else x0 = x10
 
99:
ldp x20,lr,[sp],16 // restaur 2 registers
100:
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Number N is negative.
Resultat = 3628800
Resultat = 2432902008176640000
Number N to large.
</pre>
 
=={{header|ABAP}}==
===Iterative===
<langsyntaxhighlight ABAPlang="abap">form factorial using iv_val type i.
data: lv_res type i value 1.
do iv_val times.
Line 147 ⟶ 349:
 
iv_val = lv_res.
endform.</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight ABAPlang="abap">form fac_rec using iv_val type i.
data: lv_temp type i.
 
Line 159 ⟶ 361:
multiply iv_val by lv_temp.
endif.
endform.</langsyntaxhighlight>
 
=={{header|Acornsoft Lisp}}==
 
===Recursive===
<syntaxhighlight lang="lisp">(defun factorial (n)
(cond ((zerop n) 1)
(t (times n (factorial (sub1 n))))))
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="lisp">(defun factorial (n (result . 1))
(loop
(until (zerop n) result)
(setq result (times n result))
(setq n (sub1 n))))
</syntaxhighlight>
 
=={{header|Action!}}==
Action! language does not support recursion. Another limitation are integer variables of size up to 16-bit.
<syntaxhighlight lang="action!">CARD FUNC Factorial(INT n BYTE POINTER err)
CARD i,res
 
IF n<0 THEN
err^=1 RETURN (0)
ELSEIF n>8 THEN
err^=2 RETURN (0)
FI
res=1
FOR i=2 TO n
DO
res=res*i
OD
err^=0
RETURN (res)
 
PROC Main()
INT i,f
BYTE err
 
FOR i=-2 TO 10
DO
f=Factorial(i,@err)
 
IF err=0 THEN
PrintF("%I!=%U%E",i,f)
ELSEIF err=1 THEN
PrintF("%I is negative value%E",i)
ELSE
PrintF("%I! is to big%E",i)
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Factorial.png Screenshot from Atari 8-bit computer]
<pre>
-2 is negative value
-1 is negative value
0!=1
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9! is to big
10! is to big
</pre>
 
=={{header|ActionScript}}==
===Iterative===
<langsyntaxhighlight lang="actionscript">public static function factorial(n:int):int
{
if (n < 0)
Line 173 ⟶ 446:
 
return fact;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="actionscript">public static function factorial(n:int):int
{
if (n < 0)
Line 184 ⟶ 457:
return n * factorial(n - 1);
}</langsyntaxhighlight>
 
=={{header|Ada}}==
===Iterative===
<langsyntaxhighlight lang="ada">function Factorial (N : Positive) return Positive is
Result : Positive := N;
Counter : Natural := N - 1;
Line 196 ⟶ 469:
end loop;
return Result;
end Factorial;</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="ada">function Factorial(N : Positive) return Positive is
Result : Positive := 1;
begin
Line 205 ⟶ 478:
end if;
return Result;
end Factorial;</langsyntaxhighlight>
===Numerical Approximation===
<langsyntaxhighlight lang="ada">with Ada.Numerics.Generic_Complex_Types;
with Ada.Numerics.Generic_Complex_Elementary_Functions;
with Ada.Numerics.Generic_Elementary_Functions;
Line 268 ⟶ 541:
New_Line;
end loop;
end Factorial_Numeric_Approximation;</langsyntaxhighlight>
{{out}}
<pre>
Line 285 ⟶ 558:
 
=={{header|Agda}}==
<syntaxhighlight lang="agda">module Factorial where
<lang Agda>factorial : ℕ → ℕ
 
open import Data.Nat using (ℕ ; zero ; suc ; _*_)
 
factorial : (n : ℕ) → ℕ
factorial zero = 1
factorial (suc n) = (suc n) * (factorial n</lang>)
</syntaxhighlight>
 
=={{header|Aime}}==
===Iterative===
<langsyntaxhighlight lang="aime">integer
factorial(integer n)
{
Line 304 ⟶ 582:
 
return result;
}</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="algol60">begin
comment factorial - algol 60;
integer procedure factorial(n); integer n;
begin
integer i,fact;
fact:=1;
for i:=2 step 1 until n do
fact:=fact*i;
factorial:=fact
end;
integer i;
for i:=1 step 1 until 10 do outinteger(1,factorial(i));
outstring(1,"\n")
end</syntaxhighlight>
{{out}}
<pre>
1 2 6 24 120 720 5040 40320 362880 3628800
</pre>
 
=={{header|ALGOL 68}}==
===Iterative===
<langsyntaxhighlight lang="algol68">PROC factorial = (INT upb n)LONG LONG INT:(
LONG LONG INT z := 1;
FOR n TO upb n DO z *:= n OD;
z
); ~</langsyntaxhighlight>
 
===Numerical Approximation===
Line 318 ⟶ 617:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to restricted support for ''compl''}}
<langsyntaxhighlight lang="algol68">INT g = 7;
[]REAL p = []REAL(0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
Line 348 ⟶ 647:
OD
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 364 ⟶ 663:
 
===Recursive===
<langsyntaxhighlight lang="algol68">PROC factorial = (INT n)LONG LONG INT:
CASE n+1 IN
1,1,2,6,24,120,720 # a brief lookup #
Line 370 ⟶ 669:
n*factorial(n-1)
ESAC
; ~</langsyntaxhighlight>
 
=={{header|ALGOL-M}}==
<lang>INTEGER FUNCTION FACTORIAL( N ); INTEGER N;
BEGIN
INTEGER I, FACT;
FACT := 1;
FOR I := 2 STEP 1 UNTIL N DO
FACT := FACT * I;
FACTORIAL := FACT;
END;</lang>
 
=={{header|ALGOL W}}==
Iterative solution
<langsyntaxhighlight lang="algolw">begin
% computes factorial n iteratively %
integer procedure factorial( integer value n ) ;
Line 398 ⟶ 687:
for t := 0 until 10 do write( "factorial: ", t, factorial( t ) );
 
end.</langsyntaxhighlight>
 
=={{header|ALGOL-M}}==
<syntaxhighlight lang="text">INTEGER FUNCTION FACTORIAL( N ); INTEGER N;
BEGIN
INTEGER I, FACT;
FACT := 1;
FOR I := 2 STEP 1 UNTIL N DO
FACT := FACT * I;
FACTORIAL := FACT;
END;</syntaxhighlight>
 
=={{header|AmigaE}}==
Recursive solution:
<langsyntaxhighlight lang="amigae">PROC fact(x) IS IF x>=2 THEN x*fact(x-1) ELSE 1
 
PROC main()
WriteF('5! = \d\n', fact(5))
ENDPROC</langsyntaxhighlight>
 
Iterative:
<langsyntaxhighlight lang="amigae">PROC fact(x)
DEF r, y
IF x < 2 THEN RETURN 1
r := 1; y := x;
FOR x := 2 TO y DO r := r * x
ENDPROC r</langsyntaxhighlight>
 
=={{header|AntLang}}==
AntLang is a functional language, but it isn't made for recursion - it's made for list processing.
<langsyntaxhighlight AntLanglang="antlang">factorial:{1 */ 1+range[x]} /Call: factorial[1000]</langsyntaxhighlight>
 
=={{header|Apex}}==
===Iterative===
<langsyntaxhighlight lang="apex">public static long fact(final Integer n) {
if (n < 0) {
System.debug('No negative numbers');
Line 432 ⟶ 731:
}
return ans;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="apex">public static long factRec(final Integer n) {
if (n < 0){
System.debug('No negative numbers');
Line 440 ⟶ 739:
}
return (n < 2) ? 1 : n * fact(n - 1);
}</langsyntaxhighlight>
 
=={{header|APL}}==
Both GNU APL and the DYALOG dialect of APL provides a factorial function:
<langsyntaxhighlight lang="apl"> !6
720</langsyntaxhighlight>
But, if we want to reimplement it, we can start by noting that <i>n</i>! is found by multiplying together a vector of integers 1, 2... <i>n</i>. This definition ('multiply'—'together'—'integers from 1 to'—'<i>n</i>') can be expressed directly in APL notation:
<langsyntaxhighlight lang="apl"> FACTORIAL←{×/⍳⍵} ⍝ OR: FACTORIAL←×/⍳ </langsyntaxhighlight>
And the resulting function can then be used instead of the (admittedly more convenient) builtin one:
<langsyntaxhighlight lang="apl"> FACTORIAL 6
720</langsyntaxhighlight>
{{works with|Dyalog APL}}
A recursive definition is also possible:
<syntaxhighlight lang="apl">
fac←{⍵>1 : ⍵×fac ⍵-1 ⋄ 1}
fac 5
120
</syntaxhighlight>
 
=={{header|AppleScript}}==
===Iteration===
<langsyntaxhighlight AppleScriptlang="applescript">on factorial(x)
if x < 0 then return 0
set R to 1
Line 461 ⟶ 767:
end repeat
return R
end factorial</langsyntaxhighlight>
 
===Recursion===
Line 468 ⟶ 774:
(Perhaps because the iterative code is making use of list splats)
 
<langsyntaxhighlight AppleScriptlang="applescript">-- factorial :: Int -> Int
on factorial(x)
if x > 1 then
x * (factorial(x - 1))
else if x = 1 then
1
else
01
end if
end factorial</langsyntaxhighlight>
 
===Fold===
We can also define factorial as '''foldlproduct(product, 1, enumFromTo(1, x))''',
where product is defined in terms of a fold.
 
<langsyntaxhighlight AppleScriptlang="applescript">-- FACTORIAL ------------------------------------------ FACTORIAL -----------------------
 
-- factorial :: Int -> Int
on factorial(x)
script product
on |λ|(a, b)
a * b
end |λ|
end script
foldl(product, 1, (enumFromTo(1, x))
end factorial
 
 
-- TEST --------------------------------------------- TEST -------------------------
on run
Line 506 ⟶ 807:
 
 
-- GENERIC FUNCTIONS -------------------------------------- GENERIC FUNCTIONS -------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set dxs to -1{}
repeat with i from m to n
set end of xs to i
end repeat
xs
else
set d to 1{}
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 533 ⟶ 834:
end tell
end foldl
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 544 ⟶ 846:
end script
end if
end mReturn</lang>
 
 
-- product :: [Num] -> Num
on product(xs)
script multiply
on |λ|(a, b)
a * b
end |λ|
end script
foldl(multiply, 1, xs)
end product</syntaxhighlight>
{{Out}}
<pre>39916800</pre>
 
=={{header|Applesoft BASIC}}==
===Iterative===
<lang ApplesoftBasic>100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END
 
200 N = INT(N)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
220 RETURN</lang>
===Recursive===
<lang ApplesoftBasic> 10 A = 768:L = 7
20 DATA 165,157,240,3
30 DATA 32,149,217,96
40 FOR I = A TO A + L
50 READ B: POKE I,B: NEXT
60 H = 256: POKE 12,A / H
70 POKE 11,A - PEEK (12) * H
80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1)
90 PRINT FN FA(4)</lang>http://hoop-la.ca/apple2/2013/usr-if-recursive-fn/
 
=={{header|Arendelle}}==
Line 582 ⟶ 876:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 761 ⟶ 1,055:
 
</syntaxhighlight>
</lang>
 
=={{header|ArnoldC}}==
<syntaxhighlight lang="arnoldc">LISTEN TO ME VERY CAREFULLY factorial
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
BECAUSE I'M GOING TO SAY PLEASE n
BULLS***
I'LL BE BACK 1
YOU HAVE NO RESPECT FOR LOGIC
HEY CHRISTMAS TREE product
YOU SET US UP @NO PROBLEMO
STICK AROUND n
GET TO THE CHOPPER product
HERE IS MY INVITATION product
YOU'RE FIRED n
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET DOWN @NO PROBLEMO
ENOUGH TALK
CHILL
I'LL BE BACK product
HASTA LA VISTA, BABY</syntaxhighlight>
 
=={{header|Arturo}}==
===Recursive===
 
<syntaxhighlight lang arturo="rebol">factorial: @($[n){ ][
if? n>0 {[n * factorial n-1]
else [1]
n * [factorial n-1]
]</syntaxhighlight>
} { 1 }
}</lang>
 
===Fold===
 
<syntaxhighlight lang arturo="rebol">factorial: @($[n) { ][
fold.seed:1 1..n 1 -> &0[a,b][a*&1b]
]</syntaxhighlight>
}</lang>
 
===Product===
 
<syntaxhighlight lang arturo="rebol">factorial: @($[n) -> ][product|range 1 ..n</lang>]
 
loop 1..19 [x][
print ["Factorial of" x "=" factorial x]
]</syntaxhighlight>
 
{{out}}
 
<pre>Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Factorial of 6 = 720
Factorial of 7 = 5040
Factorial of 8 = 40320
Factorial of 9 = 362880
Factorial of 10 = 3628800
Factorial of 11 = 39916800
Factorial of 12 = 479001600
Factorial of 13 = 6227020800
Factorial of 14 = 87178291200
Factorial of 15 = 1307674368000
Factorial of 16 = 20922789888000
Factorial of 17 = 355687428096000
Factorial of 18 = 6402373705728000
Factorial of 19 = 121645100408832000</pre>
 
=={{header|AsciiDots}}==
 
<syntaxhighlight lang="asciidots">
<lang AsciiDots>
/---------*--~-$#-&
| /--;---\| [!]-\
Line 792 ⟶ 1,134:
*-------+-</
\-#0----/
</syntaxhighlight>
</lang>
 
=={{header|ATS}}==
 
===Iterative===
<syntaxhighlight lang="ats">
<lang ATS>
fun
fact
Line 808 ⟶ 1,150:
val () = while (n > 0) (res := res * n; n := n - 1)
}
</syntaxhighlight>
</lang>
 
===Recursive===
<syntaxhighlight lang="ats">
<lang ATS>
fun
factorial
Line 817 ⟶ 1,159:
if n > 0 then n * factorial(n-1) else 1
// end of [factorial]
</syntaxhighlight>
</lang>
 
===Tail-recursive===
<syntaxhighlight lang="ats">
<lang ATS>
fun
factorial
Line 829 ⟶ 1,171:
loop(n, 1)
end // end of [factorial]
</syntaxhighlight>
</lang>
 
=={{header|Asymptote}}==
===Iterative===
<syntaxhighlight lang="Asymptote">real factorial(int n) {
real f = 1;
for (int i = 2; i <= n; ++i)
f = f * i;
return f;
}
 
write("The factorials for the first 5 positive integers are:");
for (int j = 1; j <= 5; ++j)
write(string(j) + "! = " + string(factorial(j)));</syntaxhighlight>
 
=={{header|AutoHotkey}}==
===Iterative===
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % factorial(4)
 
factorial(n)
Line 841 ⟶ 1,196:
result *= A_Index
Return result
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % factorial(4)
 
factorial(n)
{
return n > 1 ? n-- * factorial(n) : 1
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
===Iterative===
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
Line 864 ⟶ 1,219:
Next
Return $fact
EndFunc</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
Line 875 ⟶ 1,230:
EndIf
return $int * factorial($int - 1)
EndFunc</langsyntaxhighlight>
 
=={{header|Avail}}==
Avail has a built-in factorial method using the standard exclamation point.
<syntaxhighlight lang="avail">Assert: 7! = 5040;</syntaxhighlight>
 
Its implementation is quite simple, using iterative <code>left fold_through_</code>.
<syntaxhighlight lang="avail">Method "_`!" is [n : [0..1] | 1];
 
Method "_`!" is
[
n : [2..∞)
|
left fold 2 to n through [k : [2..∞), s : [2..∞) | k × s]
];</syntaxhighlight>
 
=={{header|AWK}}==
'''Recursive'''
<langsyntaxhighlight lang="awk">function fact_r(n)
{
if ( n <= 1 ) return 1;
return n*fact_r(n-1);
}</langsyntaxhighlight>
 
'''Iterative'''
<langsyntaxhighlight lang="awk">function fact(n)
{
if ( n < 1 ) return 1;
Line 894 ⟶ 1,263:
}
return r
}</langsyntaxhighlight>
 
=={{header|Axe}}==
'''Iterative'''
<langsyntaxhighlight lang="axe">Lbl FACT
1→R
For(I,1,r₁)
Line 904 ⟶ 1,273:
End
R
Return</langsyntaxhighlight>
 
'''Recursive'''
<langsyntaxhighlight lang="axe">Lbl FACT
r₁??1,r₁*FACT(r₁-1)
Return</langsyntaxhighlight>
 
 
=={{header|Babel}}==
 
===Iterative===
<langsyntaxhighlight lang="babel">((main
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
Line 924 ⟶ 1,292:
{dup 1 =}{ zap 1 }
{1 }{ <- 1 {iter 1 + *} -> 1 - times })
cond}))</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="babel">((main
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
Line 937 ⟶ 1,305:
{1 }{ dup 1 - fact ! *})
cond}))
</syntaxhighlight>
</lang>
 
When run, either code snippet generates the following
Line 953 ⟶ 1,321:
362880
3628800</pre>
 
=={{header|BaCon}}==
Overflow occurs at 21 or greater. Negative values treated as 0.
<lang freebasic>' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
 
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n"</lang>
 
{{out}}
<pre>prompt$ ./factorial 0
0! = 1
prompt$ ./factorial 20
20! = 2432902008176640000</pre>
 
=={{header|bash}}==
===Recursive===
<langsyntaxhighlight lang="bash">factorial()
{
if [ $1 -le 1 ]
Line 986 ⟶ 1,334:
fi
}
</syntaxhighlight>
</lang>
 
===Imperative===
<syntaxhighlight lang="bash">factorial()
{
declare -nI _result=$1
declare -i n=$2
 
_result=1
while (( n > 0 )); do
let _result*=n
let n-=1
done
}
</syntaxhighlight>
 
(the imperative version will write to a variable, and can be used as <code>factorial f 10; echo $f</code>)
 
=={{header|BASIC}}==
===Iterative===
{{works with|FreeBASIC}}
{{works with|QBasic}}
{{works with|RapidQ}}
<langsyntaxhighlight lang="freebasic">FUNCTION factorial (n AS Integer) AS Integer
DIM f AS Integer, i AS Integer
f = 1
Line 999 ⟶ 1,364:
NEXT i
factorial = f
END FUNCTION</langsyntaxhighlight>
 
===Recursive===
{{works with|FreeBASIC}}
{{works with|QBasic}}
{{works with|RapidQ}}
<langsyntaxhighlight lang="freebasic">FUNCTION factorial (n AS Integer) AS Integer
IF n < 2 THEN
factorial = 1
Line 1,010 ⟶ 1,376:
factorial = n * factorial(n-1)
END IF
END FUNCTION</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
====Iterative====
<syntaxhighlight lang="applesoftbasic">100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END
 
200 N = INT(N)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
220 RETURN</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="applesoftbasic"> 10 A = 768:L = 7
20 DATA 165,157,240,3
30 DATA 32,149,217,96
40 FOR I = A TO A + L
50 READ B: POKE I,B: NEXT
60 H = 256: POKE 12,A / H
70 POKE 11,A - PEEK (12) * H
80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1)
90 PRINT FN FA(4)</syntaxhighlight>http://hoop-la.ca/apple2/2013/usr-if-recursive-fn/
 
==={{header|BaCon}}===
Overflow occurs at 21 or greater. Negative values treated as 0.
<syntaxhighlight lang="freebasic">' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
 
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n"</syntaxhighlight>
 
{{out}}
<pre>prompt$ ./factorial 0
0! = 1
prompt$ ./factorial 20
20! = 2432902008176640000</pre>
 
==={{header|BASIC256}}===
====Iterative====
<syntaxhighlight lang="vb">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
 
function factorial(n)
factorial = 1
if n > 0 then
for p = 1 to n
factorial *= p
next p
end if
end function</syntaxhighlight>
 
====Recursive====
<syntaxhighlight lang="basic256">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
 
function factorial(n)
if n > 0 then
factorial = n * factorial(n-1)
else
factorial = 1
end if
end function</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
18! is the largest that doesn't overflow.
<syntaxhighlight lang="bbcbasic"> *FLOAT64
@% = &1010
PRINT FNfactorial(18)
END
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)</syntaxhighlight>
{{out}}
<pre>6402373705728000</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
====Iterative====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factoriali(i)
140 next i
150 sub factoriali(n) : 'Iterative
160 f = 1
170 if n > 1 then
180 for j = 2 to n
190 f = f*j
200 next j
210 endif
220 factoriali = f
230 end sub</syntaxhighlight>
 
====Recursive====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factorialr(i)
140 next i
150 sub factorialr(n) : 'Recursive
160 if n < 2 then
170 f = 1
180 else
190 f = n*factorialr(n-1)
200 endif
210 factorialr = f
220 end sub</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
Line 1,016 ⟶ 1,497:
 
====Iterative====
<langsyntaxhighlight commodorebasiclang="freebasic">10 REM FACTORIAL
20 REM COMMODORE BASIC 2.0
30 INPUT "N = 10 ";N: GOSUB 100
40 PRINT N;"! =";F
50 ENDGOTO 30
100 REM FACTORIAL CALC USING SIMPLE LOOP
110 F = 1
Line 1,026 ⟶ 1,507:
130 F = F*I
140 NEXT
150 RETURN</langsyntaxhighlight>
 
====Recursive with memoization and demo====
 
The demo stops at 13!, which is when the numbers start being formatted in scientific notation.
<syntaxhighlight lang="text">100 REM FACTORIAL
 
<lang>100 REM FACTORIAL
110 DIM F(35): F(0)=1: REM MEMOS
120 DIM S(35): SP=0: REM STACK+PTR
Line 1,047 ⟶ 1,526:
230 SP=SP-1: F(S(SP-1))=S(SP-1)*S(SP): REM MEMOIZE
240 S(SP-1)=F(S(SP-1)): REM PUSH(RESULT)
250 RETURN</langsyntaxhighlight>
 
{{Out}}
Line 1,064 ⟶ 1,543:
13 ! = 6.2270208E+09
</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">'accurate between 1-12
 
print "version 1 without function"
 
for i = 1 to 12
 
let n = i
let f = 1
 
do
 
let f = f * n
let n = n - 1
 
loop n > 0
 
print f, " ",
wait
 
next i
 
print newline, newline, "version 2 with function"
 
for i = 1 to 12
 
print factorial(i), " ",
 
next i</syntaxhighlight>
{{out| Output}}<pre>version 1 without function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600
 
version 2 with function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 </pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function Factorial_Iterative(n As Integer) As Integer
Var result = 1
For i As Integer = 2 To n
result *= i
Next
Return result
End Function
 
Function Factorial_Recursive(n As Integer) As Integer
If n = 0 Then Return 1
Return n * Factorial_Recursive(n - 1)
End Function
 
For i As Integer = 1 To 5
Print i; " =>"; Factorial_Iterative(i)
Next
 
For i As Integer = 6 To 10
Print Using "##"; i;
Print " =>"; Factorial_Recursive(i)
Next
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre> 1 => 1
2 => 2
3 => 6
4 => 24
5 => 120
6 => 720
7 => 5040
8 => 40320
9 => 362880
10 => 3628800</pre>
 
==={{header|FTCBASIC}}===
<syntaxhighlight lang="basic">define f = 1, n = 0
 
print "Factorial"
print "Enter an integer: " \
 
input n
 
do
 
let f = f * n
 
-1 n
 
loop n > 0
 
print f
pause
end</syntaxhighlight>
 
 
==={{header|Gambas}}===
<syntaxhighlight lang="gambas">
' Task: Factorial
' Language: Gambas
' Author: Sinuhe Masan (2019)
' Function factorial iterative
Function factorial_iter(num As Integer) As Long
Dim fact As Long
Dim i As Integer
fact = 1
If num > 1 Then
For i = 2 To num
fact = fact * i
Next
Endif
Return fact
End
 
' Function factorial recursive
Function factorial_rec(num As Integer) As Long
If num <= 1 Then
Return 1
Else
Return num * factorial_rec(num - 1)
Endif
End
 
Public Sub Main()
Print factorial_iter(6)
Print factorial_rec(7)
End
</syntaxhighlight>
Output:
<pre>
720
5040
</pre>
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="gwbasic">10 INPUT "Enter a non/negative integer: ", N
20 IF N < 0 THEN GOTO 10
30 F# = 1
40 IF N = 0 THEN PRINT F# : END
50 F# = F# * N
60 N = N - 1
70 GOTO 40</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 DEF FACT(N)
110 LET F=1
120 FOR I=2 TO N
Line 1,072 ⟶ 1,695:
140 NEXT
150 LET FACT=F
160 END DEF</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb"> for i =0 to 40
print " FactorialI( "; using( "####", i); ") = "; factorialI( i)
print " FactorialR( "; using( "####", i); ") = "; factorialR( i)
next i
 
wait
 
function factorialI( n)
if n >1 then
f =1
For i = 2 To n
f = f * i
Next i
else
f =1
end if
factorialI =f
end function
 
function factorialR( n)
if n <2 then
f =1
else
f =n *factorialR( n -1)
end if
factorialR =f
end function
 
end</syntaxhighlight>
 
==={{header|Microsoft Small Basic}}===
<syntaxhighlight lang="smallbasic">'Factorial - smallbasic - 05/01/2019
For n = 1 To 25
f = 1
For i = 1 To n
f = f * i
EndFor
TextWindow.WriteLine("Factorial(" + n + ")=" + f)
EndFor</syntaxhighlight>
{{out}}
<pre>
Factorial(25)=15511210043330985984000000
</pre>
 
==={{header|Minimal BASIC}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX_Basic}}
<syntaxhighlight lang="qbasic">10 PRINT "ENTER AN INTEGER:";
20 INPUT N
30 LET F = 1
40 FOR K = 1 TO N
50 LET F = F * K
60 NEXT K
70 PRINT F
80 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|PC-BASIC|any}}
<syntaxhighlight lang="qbasic">100 CLS
110 LIMITE = 13
120 FOR N = 0 TO LIMITE
130 PRINT RIGHT$(STR$(N),2);"! = ";
135 GOSUB 150
137 PRINT I
140 NEXT N
145 END
150 'factorial iterative
160 I = 1
170 IF N > 1 THEN FOR J = 2 TO N : I = I*J : NEXT J
230 RETURN</syntaxhighlight>
 
==={{header|Palo Alto Tiny BASIC}}===
<syntaxhighlight lang="basic">
10 REM FACTORIAL
20 INPUT "ENTER AN INTEGER"N
30 LET F=1
40 FOR K=1 TO N
50 LET F=F*K
60 NEXT K
70 PRINT F
80 STOP
</syntaxhighlight>
{{out}}
<pre>
ENTER AN INTEGER:7
5040
</pre>
 
==={{header|PowerBASIC}}===
<syntaxhighlight lang="powerbasic">function fact1#(n%)
local i%,r#
r#=1
for i%=1 to n%
r#=r#*i%
next
fact1#=r#
end function
 
function fact2#(n%)
if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n%
end function
 
for i%=1 to 20
print i%,fact1#(i%),fact2#(i%)
next</syntaxhighlight>
 
==={{header|PureBasic}}===
====Iterative====
<syntaxhighlight lang="purebasic">Procedure factorial(n)
Protected i, f = 1
For i = 2 To n
f = f * i
Next
ProcedureReturn f
EndProcedure</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="purebasic">Procedure Factorial(n)
If n < 2
ProcedureReturn 1
Else
ProcedureReturn n * Factorial(n - 1)
EndIf
EndProcedure</syntaxhighlight>
 
==={{header|QB64}}===
<syntaxhighlight lang="qbasic">
REDIM fac#(0)
Factorial fac#(), 655, 10, power#
PRINT power#
SUB Factorial (fac#(), n&, numdigits%, power#)
power# = 0
fac#(0) = 1
remain# = 0
stx& = 0
slog# = 0
NumDiv# = 10 ^ numdigits%
FOR fac# = 1 TO n&
slog# = slog# + LOG(fac#) / LOG(10)
FOR x& = 0 TO stx&
fac#(x&) = fac#(x&) * fac# + remain#
tx# = fac#(x&) MOD NumDiv#
remain# = (fac#(x&) - tx#) / NumDiv#
fac#(x&) = tx#
NEXT
IF remain# > 0 THEN
stx& = UBOUND(fac#) + 1
REDIM _PRESERVE fac#(stx&)
fac#(stx&) = remain#
remain# = 0
END IF
NEXT
 
scanz& = LBOUND(fac#)
DO
IF scanz& < UBOUND(fac#) THEN
IF fac#(scanz&) THEN
EXIT DO
ELSE
scanz& = scanz& + 1
END IF
ELSE
EXIT DO
END IF
LOOP
 
FOR x& = UBOUND(fac#) TO scanz& STEP -1
m$ = LTRIM$(RTRIM$(STR$(fac#(x&))))
IF x& < UBOUND(fac#) THEN
WHILE LEN(m$) < numdigits%
m$ = "0" + m$
WEND
END IF
PRINT m$; " ";
power# = power# + LEN(m$)
NEXT
power# = power# + (scanz& * numdigits%) - 1
PRINT slog#
END SUB
</syntaxhighlight>
 
====QB64_2022====
<syntaxhighlight lang="qbasic">
N = 18: DIM F AS DOUBLE ' Factorial.bas from Russia
F = 1: FOR I = 1 TO N: F = F * I: NEXT: PRINT F
'N = 5 F = 120
'N = 18 F = 6402373705728000
</syntaxhighlight>
 
==={{header|Quite BASIC}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX_Basic}}
<syntaxhighlight lang="qbasic">10 CLS
20 INPUT "Enter an integer:"; N
30 LET F = 1
40 FOR K = 1 TO N
50 LET F = F * K
60 NEXT K
70 PRINT F
80 END</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 0 to 100
print " fctrI(";right$("00";str$(i),2); ") = "; fctrI(i)
print " fctrR(";right$("00";str$(i),2); ") = "; fctrR(i)
next i
end
function fctrI(n)
fctrI = 1
if n >1 then
for i = 2 To n
fctrI = fctrI * i
next i
end if
end function
 
function fctrR(n)
fctrR = 1
if n > 1 then fctrR = n * fctrR(n -1)
end function</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
====Iterative====
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 LET FACT=1
30 FOR I=2 TO N
40 LET FACT=FACT*I
50 NEXT I
60 PRINT FACT</langsyntaxhighlight>
{{in}}
<pre>13</pre>
Line 1,088 ⟶ 1,941:
====Recursive====
A <code>GOSUB</code> is just a procedure call that doesn't pass parameters.
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 LET FACT=1
30 GOSUB 60
Line 1,097 ⟶ 1,950:
80 LET N=N-1
90 GOSUB 60
100 RETURN</langsyntaxhighlight>
{{in}}
<pre>13</pre>
Line 1,103 ⟶ 1,956:
<pre>6227020800</pre>
 
==={{header|BASIC256TI-83 BASIC}}===
TI-83 BASIC has a built-in factorial operator: x! is the factorial of x.
===Iterative===
An other way is to use a combination of prod() and seq() functions:
<lang vb>print "enter a number, n = ";
<syntaxhighlight lang="ti89b">10→N
input n
N! ---> 362880
print string(n) + "! = " + string(factorial(n))
prod(seq(I,I,1,N)) ---> 362880</syntaxhighlight>
Note: maximum integer value is:
13! ---> 6227020800
 
==={{header|TI-89 BASIC}}===
function factorial(n)
TI-89 BASIC also has the factorial function built in: x! is the factorial of x.
factorial = 1
<syntaxhighlight lang="ti89b">factorial(x)
if n > 0 then
Func
for p = 1 to n
Return Π(y,y,1,x)
factorial *= p
EndFunc</syntaxhighlight>
next p
end if
end function</lang>
 
Π is the standard product operator: <math>\overbrace{\Pi(\mathrm{expr},i,a,b)}^{\mathrm{TI-89}} = \overbrace{\prod_{i=a}^b \mathrm{expr}}^{\text{Math notation}}</math>
===Recursive===
<lang BASIC256>print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
 
==={{Header|Tiny BASIC}}===
function factorial(n)
{{works with|TinyBasic}}
if n > 0 then
<syntaxhighlight lang="basic">10 LET F = 1
factorial = n * factorial(n-1)
20 PRINT "Enter an integer."
else
30 INPUT N
factorial = 1
40 IF N = 0 THEN GOTO 80
end if
50 LET F = F * N
end function</lang>
60 LET N = N - 1
70 GOTO 40
80 PRINT F
90 END</syntaxhighlight>
 
==={{header|True BASIC}}===
====Iterative====
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">DEF FNfactorial(n)
LET f = 1
FOR i = 2 TO n
LET f = f*i
NEXT i
LET FNfactorial = f
END DEF
END</syntaxhighlight>
 
====Recursive====
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">DEF FNfactorial(n)
IF n < 2 THEN
LET FNfactorial = 1
ELSE
LET FNfactorial = n * FNfactorial(n-1)
END IF
END DEF
END</syntaxhighlight>
 
==={{header|VBA}}===
<syntaxhighlight lang="vb">Public Function factorial(n As Integer) As Long
factorial = WorksheetFunction.Fact(n)
End Function</syntaxhighlight> =={{header|VBA}}==
For numbers < 170 only
<syntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Dim i As Integer
For i = 1 To 17
Debug.Print "Factorial " & i & " , recursive : " & FactRec(i) & ", iterative : " & FactIter(i)
Next
Debug.Print "Factorial 120, recursive : " & FactRec(120) & ", iterative : " & FactIter(120)
End Sub
 
Private Function FactRec(Nb As Integer) As String
If Nb > 170 Or Nb < 0 Then FactRec = 0: Exit Function
If Nb = 1 Or Nb = 0 Then
FactRec = 1
Else
FactRec = Nb * FactRec(Nb - 1)
End If
End Function
 
Private Function FactIter(Nb As Integer)
If Nb > 170 Or Nb < 0 Then FactIter = 0: Exit Function
Dim i As Integer, F
F = 1
For i = 1 To Nb
F = F * i
Next i
FactIter = F
End Function</syntaxhighlight>
{{out}}
<pre>Factorial 1 , recursive : 1, iterative : 1
Factorial 2 , recursive : 2, iterative : 2
Factorial 3 , recursive : 6, iterative : 6
Factorial 4 , recursive : 24, iterative : 24
Factorial 5 , recursive : 120, iterative : 120
Factorial 6 , recursive : 720, iterative : 720
Factorial 7 , recursive : 5040, iterative : 5040
Factorial 8 , recursive : 40320, iterative : 40320
Factorial 9 , recursive : 362880, iterative : 362880
Factorial 10 , recursive : 3628800, iterative : 3628800
Factorial 11 , recursive : 39916800, iterative : 39916800
Factorial 12 , recursive : 479001600, iterative : 479001600
Factorial 13 , recursive : 6227020800, iterative : 6227020800
Factorial 14 , recursive : 87178291200, iterative : 87178291200
Factorial 15 , recursive : 1307674368000, iterative : 1307674368000
Factorial 16 , recursive : 20922789888000, iterative : 20922789888000
Factorial 17 , recursive : 355687428096000, iterative : 355687428096000
Factorial 120, recursive : 6,68950291344919E+198, iterative : 6,68950291344912E+198</pre>
 
==={{header|VBScript}}===
Optimized with memoization, works for numbers up to 170 (because of the limitations on Doubles), exits if -1 is input
<syntaxhighlight lang="vb">Dim lookupTable(170), returnTable(170), currentPosition, input
currentPosition = 0
 
Do While True
input = InputBox("Please type a number (-1 to quit):")
MsgBox "The factorial of " & input & " is " & factorial(CDbl(input))
Loop
 
Function factorial (x)
If x = -1 Then
WScript.Quit 0
End If
Dim temp
temp = lookup(x)
If x <= 1 Then
factorial = 1
ElseIf temp <> 0 Then
factorial = temp
Else
temp = factorial(x - 1) * x
store x, temp
factorial = temp
End If
End Function
 
Function lookup (x)
Dim i
For i = 0 To currentPosition - 1
If lookupTable(i) = x Then
lookup = returnTable(i)
Exit Function
End If
Next
lookup = 0
End Function
 
Function store (x, y)
lookupTable(currentPosition) = x
returnTable(currentPosition) = y
currentPosition = currentPosition + 1
End Function</syntaxhighlight>
 
==={{header|Visual Basic}}===
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">
Option Explicit
Sub Main()
Dim i As Variant
For i = 1 To 27
Debug.Print "Factorial(" & i & ")= , recursive : " & Format$(FactRec(i), "#,###") & " - iterative : " & Format$(FactIter(i), "#,####")
Next
End Sub 'Main
Private Function FactRec(n As Variant) As Variant
n = CDec(n)
If n = 1 Then
FactRec = 1#
Else
FactRec = n * FactRec(n - 1)
End If
End Function 'FactRec
Private Function FactIter(n As Variant)
Dim i As Variant, f As Variant
f = 1#
For i = 1# To CDec(n)
f = f * i
Next i
FactIter = f
End Function 'FactIter
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Factorial(1)= , recursive : 1 - iterative : 1
Factorial(2)= , recursive : 2 - iterative : 2
Factorial(3)= , recursive : 6 - iterative : 6
Factorial(4)= , recursive : 24 - iterative : 24
Factorial(5)= , recursive : 120 - iterative : 120
Factorial(6)= , recursive : 720 - iterative : 720
Factorial(7)= , recursive : 5,040 - iterative : 5,040
Factorial(8)= , recursive : 40,320 - iterative : 40,320
Factorial(9)= , recursive : 362,880 - iterative : 362,880
Factorial(10)= , recursive : 3,628,800 - iterative : 3,628,800
Factorial(11)= , recursive : 39,916,800 - iterative : 39,916,800
Factorial(12)= , recursive : 479,001,600 - iterative : 479,001,600
Factorial(13)= , recursive : 6,227,020,800 - iterative : 6,227,020,800
Factorial(14)= , recursive : 87,178,291,200 - iterative : 87,178,291,200
Factorial(15)= , recursive : 1,307,674,368,000 - iterative : 1,307,674,368,000
Factorial(16)= , recursive : 20,922,789,888,000 - iterative : 20,922,789,888,000
Factorial(17)= , recursive : 355,687,428,096,000 - iterative : 355,687,428,096,000
Factorial(18)= , recursive : 6,402,373,705,728,000 - iterative : 6,402,373,705,728,000
Factorial(19)= , recursive : 121,645,100,408,832,000 - iterative : 121,645,100,408,832,000
Factorial(20)= , recursive : 2,432,902,008,176,640,000 - iterative : 2,432,902,008,176,640,000
Factorial(21)= , recursive : 51,090,942,171,709,440,000 - iterative : 51,090,942,171,709,440,000
Factorial(22)= , recursive : 1,124,000,727,777,607,680,000 - iterative : 1,124,000,727,777,607,680,000
Factorial(23)= , recursive : 25,852,016,738,884,976,640,000 - iterative : 25,852,016,738,884,976,640,000
Factorial(24)= , recursive : 620,448,401,733,239,439,360,000 - iterative : 620,448,401,733,239,439,360,000
Factorial(25)= , recursive : 15,511,210,043,330,985,984,000,000 - iterative : 15,511,210,043,330,985,984,000,000
Factorial(26)= , recursive : 403,291,461,126,605,635,584,000,000 - iterative : 403,291,461,126,605,635,584,000,000
Factorial(27)= , recursive : 10,888,869,450,418,352,160,768,000,000 - iterative : 10,888,869,450,418,352,160,768,000,000
 
 
</pre>
 
==={{header|Visual Basic .NET}}===
{{trans|C#}}
{{libheader|System.Numerics}}
Various type implementations follow. No error checking, so don't try to evaluate a number less than zero, or too large of a number.
<syntaxhighlight lang="vbnet">Imports System
Imports System.Numerics
Imports System.Linq
 
Module Module1
 
' Type Double:
 
Function DofactorialI(n As Integer) As Double ' Iterative
DofactorialI = 1 : For i As Integer = 1 To n : DofactorialI *= i : Next
End Function
 
' Type Unsigned Long:
 
Function ULfactorialI(n As Integer) As ULong ' Iterative
ULfactorialI = 1 : For i As Integer = 1 To n : ULfactorialI *= i : Next
End Function
 
' Type Decimal:
 
Function DefactorialI(n As Integer) As Decimal ' Iterative
DefactorialI = 1 : For i As Integer = 1 To n : DefactorialI *= i : Next
End Function
 
' Extends precision by "dehydrating" and "rehydrating" the powers of ten
Function DxfactorialI(n As Integer) As String ' Iterative
Dim factorial as Decimal = 1, zeros as integer = 0
For i As Integer = 1 To n : factorial *= i
If factorial Mod 10 = 0 Then factorial /= 10 : zeros += 1
Next : Return factorial.ToString() & New String("0", zeros)
End Function
 
' Arbitrary Precision:
 
Function FactorialI(n As Integer) As BigInteger ' Iterative
factorialI = 1 : For i As Integer = 1 To n : factorialI *= i : Next
End Function
 
Function Factorial(number As Integer) As BigInteger ' Functional
Return Enumerable.Range(1, number).Aggregate(New BigInteger(1),
Function(acc, num) acc * num)
End Function
 
Sub Main()
Console.WriteLine("Double : {0}! = {1:0}", 20, DoFactorialI(20))
Console.WriteLine("ULong : {0}! = {1:0}", 20, ULFactorialI(20))
Console.WriteLine("Decimal : {0}! = {1:0}", 27, DeFactorialI(27))
Console.WriteLine("Dec.Ext : {0}! = {1:0}", 32, DxFactorialI(32))
Console.WriteLine("Arb.Prec: {0}! = {1}", 250, Factorial(250))
End Sub
End Module</syntaxhighlight>
{{out}}
Note that the first four are the maximum possible for their type without causing a run-time error.
<pre>Double : 20! = 2432902008176640000
ULong : 20! = 2432902008176640000
Decimal : 27! = 10888869450418352160768000000
Dec.Ext : 32! = 263130836933693530167218012160000000
Arb.Prec: 250! = 3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000
</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">// recursive
sub factorial(n)
if n > 1 then return n * factorial(n - 1) else return 1 end if
end sub
 
//iterative
sub factorial2(n)
local i, t
t = 1
for i = 1 to n
t = t * i
next
return t
end sub
 
for n = 0 to 9
print "Factorial(", n, ") = ", factorial(n)
next</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
====Iterative====
<syntaxhighlight lang="zxbasic">10 LET x=5: GO SUB 1000: PRINT "5! = ";r
999 STOP
1000 REM *************
1001 REM * FACTORIAL *
1002 REM *************
1010 LET r=1
1020 IF x<2 THEN RETURN
1030 FOR i=2 TO x: LET r=r*i: NEXT i
1040 RETURN </syntaxhighlight>
{{out}}
<pre>
5! = 120
</pre>
 
====Recursive====
Using VAL for delayed evaluation and AND's ability to return given string or empty,
we can now control the program flow within an expression in a manner akin to LISP's cond:
<syntaxhighlight lang="zxbasic">DEF FN f(n) = VAL (("1" AND n<=0) + ("n*FN f(n-1)" AND n>0)) </syntaxhighlight>
But, truth be told, the parameter n does not withstand recursive calling.
Changing the order of the product gives naught:
<syntaxhighlight lang="zxbasic">DEF FN f(n) = VAL (("1" AND n<=0) + ("FN f(n-1)*n" AND n>0))</syntaxhighlight>
Some little tricks with string slicing can get us there though:
<syntaxhighlight lang="zxbasic">DEF FN f(n) = VAL "n*FN f(n-1)*1"((n<1)*10+1 TO )</syntaxhighlight>
(lack of spaces important) will jump to the 11th character of the string ("1") on the last iteration, allowing the function call to unroll.
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
set /p x=
set /a fs=%x%-1
Line 1,140 ⟶ 2,290:
echo %y%
pause
exit</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
18! is the largest that doesn't overflow.
<lang bbcbasic> *FLOAT64
@% = &1010
PRINT FNfactorial(18)
END
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)</lang>
{{out}}
<pre>6402373705728000</pre>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">#! /usr/bin/bc -q
 
define f(x) {
Line 1,163 ⟶ 2,299:
}
f(1000)
quit</langsyntaxhighlight>
 
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program Factorial
// only works for cardinal numbers 0..N
calc main_init
log to_str(Iterative(4)) // 24
log to_str(Recursive(5)) // 120
 
calc Iterative(
n:num -- number of iterations
):num -- result
var total = 1
loop from:2 to:n index:ix
total = ix * total
return total
calc Recursive ditto
if n <= 1
return 1
else
return n * Recursive(n-1)</syntaxhighlight>
{{out}}
<pre>24
120</pre>
 
=={{header|beeswax}}==
Line 1,170 ⟶ 2,329:
Infinite loop for entering <code>n</code> and getting the result <code>n!</code>:
 
<langsyntaxhighlight lang="beeswax"> p <
_>1FT"pF>M"p~.~d
>Pd >~{Np
d <</langsyntaxhighlight>
 
Calculate <code>n!</code> only once:
 
<langsyntaxhighlight lang="beeswax"> p <
_1FT"pF>M"p~.~d
>Pd >~{;</langsyntaxhighlight>
 
Limits for UInt64 numbers apply to both examples.
Line 1,186 ⟶ 2,345:
<code>i</code> indicates that the program expects the user to enter an integer.
 
<langsyntaxhighlight lang="julia">julia> beeswax("factorial.bswx")
i0
1
Line 1,198 ⟶ 2,357:
3628800
i22
17196083355034583040</langsyntaxhighlight>
 
Input of negative numbers forces the program to quit with an error message.
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">&1\> :v v *<
^-1:_$>\:|
@.$<</langsyntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
Factorial on Church numerals in the lambda calculus is <code>λn.λf.n(λf.λn.n(f(λf.λx.n f(f x))))(λx.f)(λx.x)</code> (see https://github.com/tromp/AIT/blob/master/numerals/fac.lam) which in BLC is the 57 bits
<pre>000001010111000000110011100000010111101100111010001100010</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Fac ← ×´1+↕
! 720 ≡ Fac 6</syntaxhighlight>
 
=={{header|Bracmat}}==
Compute 10! and checking that it is 3628800, the esoteric way
<langsyntaxhighlight lang="bracmat"> (
=
. !arg:0&1
Line 1,236 ⟶ 2,403:
$ 10
: 3628800
</syntaxhighlight>
</lang>
 
This recursive lambda function is made in the following way (see http://en.wikipedia.org/wiki/Lambda_calculus):
Line 1,247 ⟶ 2,414:
or, translated to Bracmat, and computing 10!
 
<langsyntaxhighlight lang="bracmat"> ( (=(r.!arg:?r&'(.!arg:0&1|!arg*(($r)$($r))$(!arg+-1)))):?g
& (!g$!g):?f
& !f$10
)</langsyntaxhighlight>
 
The following is a straightforward recursive solution. Stack overflow occurs at some point, above 4243! in my case (Win XP).
Line 1,261 ⟶ 2,428:
Lastly, here is an iterative solution
 
<langsyntaxhighlight lang="bracmat">(factorial=
r
. !arg:?r
Line 1,267 ⟶ 2,434:
' (!arg:>1&(!arg+-1:?arg)*!r:?r)
& !r
);</langsyntaxhighlight>
 
factorial$5000
Line 1,274 ⟶ 2,441:
=={{header|Brainf***}}==
Prints sequential factorials in an infinite loop.
<langsyntaxhighlight lang="brainf***">>++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[>
+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-
]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[
>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">factorial = { x |
true? x == 0 1 { x * factorial(x - 1)}
}</langsyntaxhighlight>
 
=={{header|Bruijn}}==
 
Implementation for numbers encoded in balanced ternary using Mixfix syntax defined in the Math module:
 
<syntaxhighlight lang="bruijn">
:import std/Math .
 
factorial [∏ (+1) → 0 | [0]]
 
:test ((factorial (+10)) =? (+3628800)) ([[1]])
</syntaxhighlight>
 
=={{header|Burlesque}}==
Line 1,288 ⟶ 2,467:
Using the builtin ''Factorial'' function:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 6?!
720
</syntaxhighlight>
</lang>
 
Burlesque does not have functions nor is it iterative. Burlesque's strength are its implicit loops.
Line 1,297 ⟶ 2,476:
Following examples display other ways to calculate the factorial function:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 1 6r@pd
720
Line 1,310 ⟶ 2,489:
blsq ) 7ro)(.*){0 1 11}die!
720
</syntaxhighlight>
</lang>
 
 
=={{header|embedded C for AVR MCU}}==
=== Iterative ===
<lang c>long factorial(int n) {
long result = 1;
do {
result *= n;
while(--n);
return result;
}</lang>
 
=={{header|C}}==
=== Iterative ===
<langsyntaxhighlight lang="c">int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
Line 1,331 ⟶ 2,499:
return result;
}
</syntaxhighlight>
</lang>
 
Handle negative n (returning -1)
 
<langsyntaxhighlight lang="c">int factorialSafe(int n) {
int result = 1;
if(n<0)
Line 1,343 ⟶ 2,511:
return result;
}
</syntaxhighlight>
</lang>
 
=== Recursive ===
<langsyntaxhighlight lang="c">int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
</syntaxhighlight>
</lang>
 
Handle negative n (returning -1).
 
<langsyntaxhighlight lang="c">int factorialSafe(int n) {
return n<0 ? -1 : n == 0 ? 1 : n * factorialSafe(n - 1);
}
</syntaxhighlight>
</lang>
 
=== Tail Recursive ===
Safe with some compilers (for example: GCC with -O2, LLVM's clang)
<langsyntaxhighlight lang="c">int fac_aux(int n, int acc) {
return n < 1 ? acc : fac_aux(n - 1, acc * n);
}
Line 1,370 ⟶ 2,538:
int factorial(int n) {
return fac_aux(n, 1);
}</langsyntaxhighlight>
 
===Obfuscated===
This is simply beautiful, [http://www.ioccc.org/1995/savastio.c 1995 IOCCC winning entry by Michael Savastio], largest factorial possible : 429539!
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
 
Line 1,416 ⟶ 2,584:
19,"\n%04d") ):"%4d",l1-> lll[l] ) ; }
ll1ll(10); }
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
===Iterative===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 1,441 ⟶ 2,609:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 1,459 ⟶ 2,627:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 1,487 ⟶ 2,655:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Functional===
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,503 ⟶ 2,671:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Arbitrary Precision===
{{libheader|System.Numerics}}
Can<code>Factorial()</code> can calculate 250000200000! in underaround a40 minuteseconds over at Tio.run.<br>
<code>FactorialQ()</code> can calculate 1000000! in around 40 seconds over at Tio.run.<br><br>
<lang csharp>using System;
 
The "product tree" algorithm multiplies pairs of items on a list until there is only one item. Even though around the same number of multiply operations occurs (compared to the plain "accumulator" method), this is faster because the "bigger" numbers are generated near the end of the algorithm, instead of around halfway through. There is a significant space overhead incurred due to the creation of the temporary array to hold the partial results. The additional time overhead for array creation is negligible compared with the time savings of not dealing with the very large numbers until near the end of the algorithm.<br><br>
 
For example, for 50!, here are the number of digits created for each product for either method:<br>
plain:<br>
1 1 1 2 3 3 4 5 6 7 8 9 10 11 13 14 15 16 18 19 20 22 23 24 26 27 29 30 31 33 34 36 37 39 41 42 44 45 47 48 50 52 53 55 57 58 60 62 63 65<br>
product tree:<br>
2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 5 5 5 6 6 6 6 6 6 6 6 6 8 11 11 11 11 11 13 21 21 23 42 65<br>
 
One can see the plain method increases linearly up to the final value of 65. The product tree method stays low for quite awhile, then jumps up at the end.<br>
 
For 200000!, when one sums up the number of digits of each product for all 199999 multiplications, the plain method is nearly 93 billion, while the product tree method is only about 17.3 million.
<syntaxhighlight lang="csharp">using System;
using System.Numerics;
using System.Linq;
Line 1,520 ⟶ 2,701:
{
return Enumerable.Range(1, number).Aggregate(new BigInteger(1), (acc, num) => acc * num);
}
 
static public BI FactorialQ(int number) // functional quick, uses prodtree method
{
var s = Enumerable.Range(1, number).Select(num => new BI(num)).ToArray();
int top = s.Length, nt, i, j;
while (top > 1) {
for (i = 0, j = top, nt = top >> 1; i < nt; i++) s[i] *= s[--j];
top = nt + ((top & 1) == 1 ? 1 : 0);
}
return s[0];
}
 
Line 1,526 ⟶ 2,718:
Console.WriteLine(Factorial(250));
}
}</langsyntaxhighlight>
{{out}}
<pre>3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000</pre>
Line 1,532 ⟶ 2,724:
=={{header|C++}}==
The C versions work unchanged with C++, however, here is another possibility using the STL and boost:
<langsyntaxhighlight lang="cpp">#include <boost/iterator/counting_iterator.hpp>
#include <algorithm>
 
Line 1,539 ⟶ 2,731:
// last is one-past-end
return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}</langsyntaxhighlight>
 
===Iterative===
This version of the program is iterative, with a while loop.
<langsyntaxhighlight lang="cpp">//iteration with while
long long int factorial(long long int n)
{
Line 1,550 ⟶ 2,742:
r *= n--;
return r;
}</langsyntaxhighlight>
 
===Template===
<langsyntaxhighlight lang="cpp">template <int N>
struct Factorial
{
Line 1,571 ⟶ 2,763:
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}</langsyntaxhighlight>
 
===Compare all Solutions (except the meta)===
<langsyntaxhighlight lang="cpp">#include <iostreamalgorithm>
#include <chrono>
#include <vectoriostream>
#include <numeric>
#include <algorithmvector>
#include <boost/iterator/counting_iterator.hpp>
 
using ulli = unsigned long long int;
//bad style do-while and wrong for Factorial1(0LL) -> 0 !!!
 
long long int Factorial1(long long int m_nValue)
// bad style do-while and wrong for Factorial1(0LL) -> 0 !!!
{
ulli Factorial1(ulli m_nValue) {
long long int result=m_nValue;
long longulli intresult result_next= m_nValue;
ulli result_next;
long long int pc = m_nValue;
ulli pc = m_nValue;
do
do {
result_next = result * (pc - 1);
result = result_next;
pc--;
} while (pc > 2);
m_nValue =return result;
return m_nValue;
}
 
// iteration with while
long long intulli Factorial2(long long intulli n) {
ulli r = 1;
{
long longwhile int(1 r< = 1;n)
r *= n--;
while(1<n)
return r *= n--;
return r;
}
 
// recursive
//recrusive
long long intulli Factorial3(long long intulli n) {
return n < 2 ? 1 : n * Factorial3(n - 1);
{
return n<2 ? 1 : n*Factorial3(n-1);
}
 
// tail recursive
inline long long intulli _fac_aux(long long intulli n, long long intulli acc) {
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
long long intulli Factorial4(long long intulli n) {
return _fac_aux(n, 1);
{
return _fac_aux(n,1);
}
 
// accumulate with functor
long long intulli Factorial5(long long intulli n) {
// last is one-past-end
{
return std::accumulate(boost::counting_iterator<ulli>(1ULL),
// last is one-past-end
return std::accumulate( boost::counting_iterator<long long intulli>(1LLn + 1ULL), 1ULL,
boost std::counting_iteratormultiplies<long long intulli>(n+1LL), 1LL, );
}
std::multiplies<long long int>() );
 
}
// accumulate with lambda
ulli Factorial6(ulli n) {
//accumulate with lamda
// last is one-past-end
long long int Factorial6(long long int n)
return std::accumulate(boost::counting_iterator<ulli>(1ULL),
{
boost::counting_iterator<ulli>(n + 1ULL), 1ULL,
// last is one-past-end
[](ulli a, ulli b) { return a * b; });
return std::accumulate(boost::counting_iterator<long long int>(1LL),
}
boost::counting_iterator<long long int>(n+1LL), 1LL,
 
[](long long int a, long long int b) { return a*b; } );
int main() {
}
ulli v = 20; // max value with unsigned long long int
ulli result;
int main()
std::cout << std::fixed;
{
using duration = std::chrono::duration<double, std::micro>;
int v = 55;
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial1(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "do-while(1) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::chrono::duration<double, std::milli> ms = t2 - t1;
std::cout << std::fixed << "do-while(1) result " << result
<< " took " << ms.count() << " ms\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial2(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "while(2) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::chrono::duration<double, std::milli> ms = t2 - t1;
std::cout << std::fixed << "while(2) result " << result
<< " took " << ms.count() << " ms\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial3(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "recursive(3) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::chrono::duration<double, std::milli> ms = t2 - t1;
std::cout << std::fixed << "recusive(3) result " << result
<< " took " << ms.count() << " ms\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial3(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "tail recursive(4) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::chrono::duration<double, std::milli> ms = t2 - t1;
std::cout << std::fixed << "tail recusive(4) result " << result
<< " took " << ms.count() << " ms\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial5(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::durationcout <<double, "std::milli>accumulate(5) ms = result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::cout << std::fixed << "std::accumulate(5) result " << result
<< " took " << ms.count() << " ms\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
auto result = Factorial6(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::durationcout <<double, "std::milli>accumulate mslambda(6) =result " << result << " took " << duration(t2 - t1).count() << " µs\n";
std::cout << std::fixed << "std::accumulate lamda(6) result " << result
<< " took " << ms.count() << " ms\n";
}
}</langsyntaxhighlight>
<pre>do-while(1) result 2432902008176640000 took 0.110000 µs
<pre>
do-while(12) result 67114893446888816642432902008176640000 took 0.000808078000 msµs
whilerecursive(23) result 67114893446888816642432902008176640000 took 0.000725057000 msµs
recusivetail recursive(34) result 67114893446888816642432902008176640000 took 0.000730056000 msµs
tail recusivestd::accumulate(45) result 67114893446888816642432902008176640000 took 0.000705056000 msµs
std::accumulate lambda(56) result 67114893446888816642432902008176640000 took 0.000705079000 msµs
std::accumulate lamda(6) result 6711489344688881664 took 0.000722 ms
</pre>
 
=={{header|C3}}==
=== Iterative ===
<syntaxhighlight lang="c3">fn int factorial(int n)
{
int result = 1;
for (int i = 1; i <= n; ++i)
{
result *= i;
}
return result;
}
</syntaxhighlight>
=== Recursive ===
<syntaxhighlight lang="c3"> fn int factorial(int n)
{
return n == 0 ? 1 : n * factorial(n - 1);
}
</syntaxhighlight>
 
=== Recursive macro ===
In this case the value of x is compiled to a constant.
<syntaxhighlight lang="c3">macro int factorial($n)
{
$if ($n == 0):
return 1;
$else:
return $n * @factorial($n - 1);
$endif;
}
 
fn void test()
{
int x = @factorial(10);
}
</syntaxhighlight>
 
=={{header|Cat}}==
Taken direct from the Cat manual:
<langsyntaxhighlight Catlang="cat">define rec_fac
{ dup 1 <= [pop 1] [dec rec_fac *] if }</langsyntaxhighlight>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
Integer? recursiveFactorial(Integer n) =>
Line 1,731 ⟶ 2,943:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">proc fac(n) {
var r = 1;
for i in 1..n do
Line 1,740 ⟶ 2,952:
return r;
}</langsyntaxhighlight>
 
=={{header|Chef}}==
<langsyntaxhighlight Cheflang="chef">Caramel Factorials.
 
Only reads one value.
Line 1,759 ⟶ 2,971:
Pour contents of the 1st mixing bowl into the 1st baking dish.
 
Serves 1.</langsyntaxhighlight>
 
=={{header|ChucK}}==
===Recursive===
<syntaxhighlight lang="c">
0 => int total;
fun int factorial(int i)
Line 1,774 ⟶ 2,986:
return total;
}
 
</lang>
// == another way
fun int factorial(int x)
{
if (x <= 1 ) return 1;
else return x * factorial (x - 1);
}
 
// call
factorial (5) => int answer;
 
// test
if ( answer == 120 ) <<<"success">>>;
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="text">
1 => int total;
fun int factorial(int i)
Line 1,787 ⟶ 3,013:
return total;
}
</syntaxhighlight>
</lang>
 
=={{header|Clay}}==
Obviously there’s more than one way to skin a cat. Here’s a selection — recursive, iterative, and “functional” solutions.
<langsyntaxhighlight Claylang="clay">factorialRec(n) {
if (n == 0) return 1;
return n * factorialRec(n - 1);
Line 1,804 ⟶ 3,030:
factorialFold(n) {
return reduce(multiply, 1, range(1, n + 1));
}</langsyntaxhighlight>
 
We could also do it at compile time, because — hey — why not?
 
<langsyntaxhighlight Claylang="clay">[n|n > 0] factorialStatic(static n) = n * factorialStatic(static n - 1);
overload factorialStatic(static 0) = 1;</langsyntaxhighlight>
 
Because a literal 1 has type Int32, these functions receive and return numbers of that type. We must be a bit more careful if we wish to permit other numeric types (e.g. for larger integers).
 
<langsyntaxhighlight Claylang="clay">[N|Integer?(N)] factorial(n: N) {
if (n == 0) return N(1);
return n * factorial(n - 1);
}</langsyntaxhighlight>
 
And testing:
 
<langsyntaxhighlight Claylang="clay">main() {
println(factorialRec(5)); // 120
println(factorialIter(5)); // 120
Line 1,826 ⟶ 3,052:
println(factorialStatic(static 5)); // 120
println(factorial(Int64(20))); // 2432902008176640000
}</langsyntaxhighlight>
 
=={{header|CLIPS}}==
<lang lisp> (deffunction factorial (?a)
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
else
(if (= ?a 0) then
1
else
(* ?a (factorial (- ?a 1))))))</lang>
 
=={{header|Clio}}==
 
=== Recursive ===
<langsyntaxhighlight lang="clio">
fn factorial n:
if n <= 1: n
Line 1,848 ⟶ 3,064:
 
10 -> factorial -> print
</syntaxhighlight>
</lang>
 
=={{header|CLIPS}}==
<syntaxhighlight lang="lisp"> (deffunction factorial (?a)
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
else
(if (= ?a 0) then
1
else
(* ?a (factorial (- ?a 1))))))</syntaxhighlight>
 
=={{header|Clojure}}==
 
=== Folding ===
<langsyntaxhighlight lang="lisp">(defn factorial [x]
(apply *' (range 2 (inc x))))</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang="lisp">(defn factorial [x]
(if (< x 2)
1
(*' x (factorial (dec x)))))</langsyntaxhighlight>
 
=== Tail recursive ===
<langsyntaxhighlight lang="lisp">(defn factorial [x]
(loop [x x
acc 1]
(if (< x 2)
acc
(recur (dec x) (*' acc x)))))</langsyntaxhighlight>
 
=== Trampolining ===
<syntaxhighlight lang="lisp">(defn factorial
([x] (trampoline factorial x 1))
([x acc]
(if (< x 2)
acc
#(factorial (dec x) (*' acc x)))))</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">factorial = proc (n: int) returns (int) signals (negative)
if n<0 then signal negative
elseif n=0 then return(1)
else return(n * factorial(n-1))
end
end factorial
 
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(0, 10) do
fac: int := factorial(i)
stream$putl(po, int$unparse(i) || "! = " || int$unparse(fac))
end
end start_up</syntaxhighlight>
{{out}}
<pre>0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800</pre>
 
=={{header|CMake}}==
<langsyntaxhighlight lang="cmake">function(factorial var n)
set(product 1)
foreach(i RANGE 2 ${n})
Line 1,880 ⟶ 3,143:
 
factorial(f 12)
message("12! = ${f}")</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 1,887 ⟶ 3,150:
=== Intrinsic Function ===
COBOL includes an intrinsic function which returns the factorial of its argument.
<langsyntaxhighlight lang="cobol">MOVE FUNCTION FACTORIAL(num) TO result</langsyntaxhighlight>
 
=== Iterative ===
{{works with|GnuCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. factorial.
FUNCTION-ID. factorial_iterative.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(1038).
 
LINKAGE SECTION.
01 n PIC 9(1038).
01 ret PIC 9(1038).
 
PROCEDURE DIVISION USING BY VALUE n RETURNING ret.
MOVE 1 TO ret
PERFORM VARYING i FROM 2 BY 1 UNTIL n < i
MULTIPLY i BY ret
END-PERFORM
GOBACK.
 
.</lang>
END FUNCTION factorial_iterative.
</syntaxhighlight>
 
=== Recursive ===
{{works with|Visual COBOL}}
{{works with|GnuCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. factorial.
FUNCTION-ID. factorial_recursive.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 prev-n PIC 9(1038).
 
LINKAGE SECTION.
01 n PIC 9(1038).
01 ret PIC 9(1038).
 
PROCEDURE DIVISION USING BY VALUE n RETURNING ret.
IF n = 0
Line 1,929 ⟶ 3,196:
ELSE
SUBTRACT 1 FROM n GIVING prev-n
MULTIPLY n BY facfactorial_recursive(prev-n) GIVING ret
END-IF
GOBACK.
 
.</lang>
END FUNCTION factorial_recursive.
</syntaxhighlight>
 
=== Test ===
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. factorial_test.
 
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION factorial_iterative
FUNCTION factorial_recursive.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(38).
 
PROCEDURE DIVISION.
DISPLAY
"i = "
WITH NO ADVANCING
END-DISPLAY.
ACCEPT i END-ACCEPT.
DISPLAY SPACE END-DISPLAY.
 
DISPLAY
"factorial_iterative(i) = "
factorial_iterative(i)
END-DISPLAY.
 
DISPLAY
"factorial_recursive(i) = "
factorial_recursive(i)
END-DISPLAY.
 
GOBACK.
 
END PROGRAM factorial_test.
</syntaxhighlight>
 
{{out}}
<pre>
i = 14
 
factorial_iterative(i) = 00000000000000000000000000087178291200
factorial_recursive(i) = 00000000000000000000000000087178291200
</pre>
 
=={{header|CoffeeScript}}==
Line 1,939 ⟶ 3,254:
 
=== Recursive ===
<langsyntaxhighlight lang="coffeescript">fac = (n) ->
if n <= 1
1
else
n * fac n-1</langsyntaxhighlight>
 
=== Functional ===
{{works with|JavaScript|1.8}} (See [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce MDC])
<langsyntaxhighlight lang="javascript">fac = (n) ->
[1..n].reduce (x,y) -> x*y</langsyntaxhighlight>
 
=={{header|Comal}}==
Recursive:
<langsyntaxhighlight Comallang="comal"> PROC Recursive(n) CLOSED
r:=1
IF n>1 THEN
Line 1,958 ⟶ 3,273:
ENDIF
RETURN r
ENDPROC Recursive</langsyntaxhighlight>
 
=={{header|Comefrom0x10}}==
Line 1,964 ⟶ 3,279:
This is iterative; recursion is not possible in Comefrom0x10.
 
<langsyntaxhighlight lang="cf0x10">n = 5 # calculates n!
acc = 1
 
Line 1,978 ⟶ 3,293:
n = n - 1
 
acc # prints the result</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Recursive:
<langsyntaxhighlight lang="lisp">(defun factorial (n)
(if (zerop n) 1 (* n (factorial (1- n)))))</langsyntaxhighlight>
 
or
 
<syntaxhighlight lang="lisp">(defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))))</syntaxhighlight>
 
Tail Recursive:
<langsyntaxhighlight lang="lisp">(defun factorial (n &optional (m 1))
(if (zerop n) m (factorial (1- n) (* m n))))</langsyntaxhighlight>
 
Iterative:
<langsyntaxhighlight lang="lisp">(defun factorial (n)
"Calculates N!"
(loop for result = 1 then (* result i)
for i from 2 to n
finally (return result)))</langsyntaxhighlight>
 
Functional:
<langsyntaxhighlight lang="lisp">(defun factorial (n)
(reduce #'* (loop for i from 1 to n collect i)))</langsyntaxhighlight>
 
===Alternate solution===
I use [https://franz.com/downloads/clp/survey{{Works with|Allegro CL |10.1]}}
 
<syntaxhighlight lang="lisp">;; Project : Factorial
<lang lisp>
;; Project : Factorial
 
(defun factorial (n)
Line 2,010 ⟶ 3,329:
(t (* n (factorial (- n 1))))))
(format t "~a" "factorial of 8: ")
(factorial 8)</syntaxhighlight>
</lang>
Output:
<pre>factorial of 8: 40320</pre>
<pre>
factorial of 8: 40320
</pre>
 
=={{header|Computer/zero Assembly}}==
Both these programs find <math>x</math>!. Values of <math>x</math> higher than 5 are not supported, because their factorials will not fit into an unsigned byte.
===Iterative===
<langsyntaxhighlight lang="czasm"> LDA x
BRZ done_i ; 0! = 1
 
Line 2,062 ⟶ 3,378:
n: 0
 
x: 5</langsyntaxhighlight>
 
===Lookup===
Since there is only a small range of possible values of <math>x</math>, storing the answers and looking up the one we want is much more efficient than actually calculating them. This lookup version uses 5 bytes of code and 7 bytes of data and finds 5! in 5 instructions, whereas the iterative solution uses 23 bytes of code and 6 bytes of data and takes 122 instructions to find 5!.
<langsyntaxhighlight lang="czasm"> LDA load
ADD x
STA load
Line 2,080 ⟶ 3,396:
120
 
x: 5</langsyntaxhighlight>
 
=={{header|Coq}}==
<syntaxhighlight lang="coq">
Fixpoint factorial (n : nat) : nat :=
match n with
| 0 => 1
| S k => (S k) * (factorial k)
end.
</syntaxhighlight>
 
=={{header|Crystal}}==
===Iterative===
<langsyntaxhighlight lang="crystal">def factorial(x : Int)
ans = 1
(1..x).each do |i|
Line 2,090 ⟶ 3,415:
end
return ans
end</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="crystal">def factorial(x : Int)
if x <= 1
return 1
end
return x * factorial(x - 1)
end</langsyntaxhighlight>
 
=={{header|D}}==
===Iterative Version===
<langsyntaxhighlight lang="d">uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
Line 2,120 ⟶ 3,445:
// Computed and printed at run-time.
12.factorial.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>479001600u
Line 2,126 ⟶ 3,451:
 
===Recursive Version===
<langsyntaxhighlight lang="d">uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
Line 2,144 ⟶ 3,469:
// Computed and printed at run-time.
12.factorial.writeln;
}</langsyntaxhighlight>
(Same output.)
 
===Functional Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
uint factorial(in uint n) pure nothrow @nogc
Line 2,163 ⟶ 3,488:
// Computed and printed at run-time.
12.factorial.writeln;
}</langsyntaxhighlight>
(Same output.)
 
===Tail Recursive (at run-time, with DMD) Version===
<langsyntaxhighlight lang="d">uint factorial(in uint n) pure nothrow
in {
assert(n <= 12);
Line 2,188 ⟶ 3,513:
// Computed and printed at run-time.
12.factorial.writeln;
}</langsyntaxhighlight>
(Same output.)
 
=={{header|Dart}}==
===Recursive===
<langsyntaxhighlight lang="dart">int fact(int n) {
if(n<0) {
throw new IllegalArgumentException('Argument less than 0');
Line 2,203 ⟶ 3,528:
print(fact(10));
print(fact(-1));
}</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="dart">int fact(int n) {
if(n<0) {
throw new IllegalArgumentException('Argument less than 0');
Line 2,219 ⟶ 3,544:
print(fact(10));
print(fact(-1));
}</langsyntaxhighlight>
 
=={{header|dc}}==
This factorial uses tail recursion to iterate from ''n'' down to 2. Some implementations, like [[OpenBSD dc]], optimize the tail recursion so the call stack never overflows, though ''n'' might be large.
<langsyntaxhighlight lang="dc">[*
* (n) lfx -- (factorial of n)
*]sz
Line 2,241 ⟶ 3,566:
* For example, print the factorial of 50.
*]sz
50 lfx psz</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
===Iterative===
<lang dejavu>factorial:
1
while over:
* over
swap -- swap
drop swap</lang>
===Recursive===
<lang dejavu>factorial:
if dup:
* factorial -- dup
else:
1 drop</lang>
 
=={{header|Delphi}}==
===Iterative===
<langsyntaxhighlight Delphilang="delphi">program Factorial1;
 
{$APPTYPE CONSOLE}
Line 2,275 ⟶ 3,585:
begin
Writeln('5! = ', FactorialIterative(5));
end.</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Delphilang="delphi">program Factorial2;
 
{$APPTYPE CONSOLE}
Line 2,292 ⟶ 3,602:
begin
Writeln('5! = ', FactorialRecursive(5));
end.</langsyntaxhighlight>
 
===Tail Recursive===
<langsyntaxhighlight Delphilang="delphi">program Factorial3;
 
{$APPTYPE CONSOLE}
Line 2,318 ⟶ 3,628:
begin
Writeln('5! = ', FactorialTailRecursive(5));
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* Note that ulong is 32 bits, so fac(12) is the largest
* supported value. This is why the input parameter
* is a byte. The parameters are all unsigned. */
proc nonrec fac(byte n) ulong:
byte i;
ulong rslt;
rslt := 1;
for i from 2 upto n do
rslt := rslt * i
od;
rslt
corp
 
proc nonrec main() void:
byte i;
for i from 0 upto 12 do
writeln(i:2, "! = ", fac(i):9)
od
corp</syntaxhighlight>
{{out}}
<pre> 0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600</pre>
 
=={{header|Dragon}}==
<syntaxhighlight lang="text">select "std"
factorial = 1
n = readln()
Line 2,329 ⟶ 3,674:
}
showln "factorial of " + n + " is " + factorial
</syntaxhighlight>
</lang>
 
=={{header|DWScript}}==
Note that ''Factorial'' is part of the standard DWScript maths functions.
===Iterative===
<langsyntaxhighlight lang="delphi">function IterativeFactorial(n : Integer) : Integer;
var
i : Integer;
Line 2,341 ⟶ 3,686:
for i := 2 to n do
Result *= i;
end;</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="delphi">function RecursiveFactorial(n : Integer) : Integer;
begin
if n>1 then
Result := RecursiveFactorial(n-1)*n
else Result := 1;
end;</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func factorial(n) {
if n < 2 {
1
Line 2,358 ⟶ 3,703:
n * factorial(n - 1)
}
}</langsyntaxhighlight>
 
=={{header|Dylan}}==
Line 2,364 ⟶ 3,709:
=== Functional ===
 
<langsyntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
Line 2,372 ⟶ 3,717:
end
end method;
</syntaxhighlight>
</lang>
 
=== Iterative ===
 
<langsyntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
Line 2,388 ⟶ 3,733:
end
end method;
</syntaxhighlight>
</lang>
 
=== Recursive ===
 
<langsyntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
Line 2,406 ⟶ 3,751:
loop(n)
end method;
</syntaxhighlight>
</lang>
 
=== Tail recursive ===
 
<langsyntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
Line 2,427 ⟶ 3,772:
loop(n, n)
end method;
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
===Iterative===
<syntaxhighlight lang="dejavu">factorial:
1
while over:
* over
swap -- swap
drop swap</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="dejavu">factorial:
if dup:
* factorial -- dup
else:
1 drop</syntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
def factorial(n) {
return accum 1 for i in 2..n { _ * i }
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>func factorial n . r .
func factorial n .
r = 1
i r = 21
while for i <= 2 to n
r = r *= i
i += 1.
return r
.
.
callprint factorial 7 r
</syntaxhighlight>
print r</lang>
 
=={{header|EchoLisp}}==
===Iterative===
<langsyntaxhighlight lang="scheme">
(define (fact n)
(for/product ((f (in-range 2 (1+ n)))) f))
(fact 10)
→ 3628800
</syntaxhighlight>
</lang>
===Recursive with memoization===
<langsyntaxhighlight lang="scheme">
(define (fact n)
(if (zero? n) 1
Line 2,464 ⟶ 3,824:
(fact 10)
→ 3628800
</syntaxhighlight>
</lang>
===Tail recursive===
<langsyntaxhighlight lang="scheme">
(define (fact n (acc 1))
(if (zero? n) acc
Line 2,472 ⟶ 3,832:
(fact 10)
→ 3628800
</syntaxhighlight>
</lang>
===Primitive===
<langsyntaxhighlight lang="scheme">
(factorial 10)
→ 3628800
</syntaxhighlight>
</lang>
===Numerical approximation===
<langsyntaxhighlight lang="scheme">
(lib 'math)
math.lib v1.13 ® EchoLisp
(gamma 11)
→ 3628800.0000000005
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module ShowFactorials {
static <Value extends IntNumber> Value factorial(Value n) {
assert:arg n >= Value.zero();
return n <= Value.one() ? n : n * factorial(n-Value.one());
}
 
@Inject Console console;
void run() {
// 128-bit test
UInt128 bigNum = 34;
console.print($"factorial({bigNum})={factorial(bigNum)}");
 
// 64-bit test
for (Int i : 10..-1) {
console.print($"factorial({i})={factorial(i)}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
factorial(34)=295232799039604140847618609643520000000
factorial(10)=3628800
factorial(9)=362880
factorial(8)=40320
factorial(7)=5040
factorial(6)=720
factorial(5)=120
factorial(4)=24
factorial(3)=6
factorial(2)=2
factorial(1)=1
factorial(0)=0
 
2023-01-19 10:14:52.716 Service "ShowFactorials" (id=1) at ^ShowFactorials (CallLaterRequest: native), fiber 1: Unhandled exception: IllegalArgument: "n >= Value.zero()": n=-1, Value.zero()=0, Value=Int
at factorial(Type<IntNumber>, factorial(?)#Value) (test.x:5)
at run() (test.x:19)
at ^ShowFactorials (CallLaterRequest: native)
</pre>
 
=={{header|EDSAC order code}}==
<syntaxhighlight lang="edsac">
[Demo of subroutine to calculate factorial.
EDSAC program, Initial Orders 2.]
 
[Arrange the storage]
T45K P56F [H parameter: subroutine for factorial]
T46K P80F [N parameter: library subroutine P7 to print integer]
T47K P128F [M parameter: main routine]
 
[================================ H parameter ================================]
E25K TH
[Subroutine for N factorial. Works for 0 <= N <= 13 (no checking done).
Input: 17-bit integer N in 6F (preserved).
Output: 35-bit N factorial is returned in 0D.
Workspace: 7F]
GK
A3F T19@ [plant return link as usual]
TD [clear the whole of 0D, including the sandwich bit]
A20@ TF [0D := 35-bit 1]
A6F T7F [7F = current factor, initialize to N]
E15@ [jump into middle of loop]
[Head of loop: here with 7F = factor, acc = factor - 2]
[8] H7F [mult reg := factor]
A20@ [acc := factor - 1]
T7F [update factor, clear acc]
VD [acc := 0D times factor]
L64F L64F [shift 16 left (as 8 + 8) for integer scaling]
TD [update product, clear acc]
[15] A7F S2F [is factor >= 2 ? (2F permanently holds P1F)]
E8@ [if so, loop back]
T7F [clear acc on exit]
[19] ZF [(planted) return to caller]
[20] PD [constant: 17-bit 1]
 
[================================ M parameter ================================]
E25K TM GK
[Main routine]
[Teleprinter characters]
[0] K2048F [1] #F [letters mode, figures mode]
[2] FF [3] AF [4] CF [5] VF [F, A, C, equals]
[6] !F [7] @F [8] &F [space, carriage return, line feed]
 
[Enter here with acc = 0]
[9] TD [clear the whole of 0D, including the sandwich bit]
A33@ [load 17-bit number N whose factorial is required]
UF [store N in 0D, extended to 35 bits for printing]
T6F [also store N in 6F, for factorial subroutine]
O1@ [set teleprinter to figures]
[14] A14@ GN [print N (print subroutine preserves 6F)]
 
[Print " FAC = " (EDSAC teleprinter had no exclamation mark)]
O@ O6@ O2@ O3@ O4@ O1@ O6@ O5@ O6@
 
[25] A25@ GH [call the above subroutine, 0D := N factorial]
[27] A27@ GN [call subroutine to print 0D]
O7@ O8@ [print CR, LF]
O1@ [print dummy character to flush teleprinter buffer]
ZF [stop]
[33] P6D [constant: 17-bit 13]
 
[================================ N parameter ================================]
E25K TN
[Library subroutine P7, prints long strictly positive integer in 0D.
10 characters, right justified, padded left with spaces.
Even address; 35 storage locations; working position 4D.]
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[============================= M parameter again =============================]
E25K TM GK
E9Z [define entry point]
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
{{out}}
<pre>
13 FAC = 6227020800
</pre>
 
=={{header|EGL}}==
===Iterative===
<syntaxhighlight lang="egl">
<lang EGL>
function fact(n int in) returns (bigint)
if (n < 0)
Line 2,500 ⟶ 3,983:
return (ans);
end
</syntaxhighlight>
</lang>
===Recursive===
<syntaxhighlight lang="egl">
<lang EGL>
function fact(n int in) returns (bigint)
if (n < 0)
Line 2,514 ⟶ 3,997:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
note
description: "recursive and iterative factorial example of a positive integer."
Line 2,568 ⟶ 4,051:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Tail recursive version:
 
<langsyntaxhighlight Elalang="ela">fact = fact' 1L
where fact' acc 0 = acc
fact' acc n = fact' (n * acc) (n - 1)</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Factorial do
# Simple recursive function
def fac(0), do: 1
Line 2,602 ⟶ 4,085:
def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)
 
end</langsyntaxhighlight>
 
=={{header|Elm}}==
 
==={{header|Recursive}}===
 
<langsyntaxhighlight lang="elm">
factorial : Int -> Int
factorial n =
if n < 1 then 1 else n*factorial(n-1)
</syntaxhighlight>
</lang>
 
==={{header|Tail Recursive}}===
 
<langsyntaxhighlight lang="elm">
factorialAux : Int -> Int -> Int
factorialAux a acc =
Line 2,624 ⟶ 4,107:
factorial a =
factorialAux a 1
</syntaxhighlight>
</lang>
 
==={{header|Functional}}===
 
<langsyntaxhighlight lang="elm">
import List exposing (product, range)
 
Line 2,634 ⟶ 4,117:
factorial a =
product (range 1 a)
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang ="lisp">(defun fact (n)
;; Functional (most elegant and best suited to Lisp dialects):
"n is an integer, this function returns n!, that is n * (n - 1)
(defun fact (n)
* (n - 2)....* 4 * 3 * 2 * 1"
"Return the factorial of integer N, which require to be positive or 0."
(cond
;; Elisp won't do any type checking automatically, so
((= n 1) 1)
;; good practice would be doing that ourselves:
(t (* n (fact (1- n))))))</lang>
(if (not (and (integerp n) (>= n 0)))
(error "Function fact (N): Not a natural number or 0: %S" n))
;; But the actual code is very short:
(apply '* (number-sequence 1 n)))
;; (For N = 0, number-sequence returns the empty list, resp. nil,
;; and the * function works with zero arguments, returning 1.)
</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
<lang lisp>(defun fact (n) (apply '* (number-sequence 1 n)))</lang>
;; Recursive:
(defun fact (n)
"Return the factorial of integer N, which require to be positive or 0."
(if (not (and (integerp n) (>= n 0))) ; see above
(error "Function fact (N): Not a natural number or 0: %S" n))
(cond ; (or use an (if ...) with an else part)
((or (= n 0) (= n 1)) 1)
(t (* n (fact (1- n))))))
</syntaxhighlight>
 
Both of these only work up to N = 19, beyond which arithmetic overflow seems to happen.
The <code>calc</code> package (which comes with Emacs) has a builtin <code>fact()</code>. It automatically uses the bignums implemented by <code>calc</code>.
 
<langsyntaxhighlight lang="lisp">(require 'calc)
(calc-eval "fact(30)")
=>
"265252859812191058636308480000000"</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun iterative = int by int n
int result = 1
for int i = 2; i <= n; ++i do result *= i end
return result
end
fun recursive = int by int n do return when(n <= 0, 1, n * recursive(n - 1)) end
writeLine("n".padStart(2, " ") + " " + "iterative".padStart(19, " ") + " " + "recursive".padStart(19, " "))
for int n = 0; n < 21; ++n
write((text!n).padStart(2, " "))
write(" " + (text!iterative(n)).padStart(19, " "))
write(" " + (text!recursive(n)).padStart(19, " "))
writeLine()
end
</syntaxhighlight>
{{out}}
<pre>
n iterative recursive
0 1 1
1 1 1
2 2 2
3 6 6
4 24 24
5 120 120
6 720 720
7 5040 5040
8 40320 40320
9 362880 362880
10 3628800 3628800
11 39916800 39916800
12 479001600 479001600
13 6227020800 6227020800
14 87178291200 87178291200
15 1307674368000 1307674368000
16 20922789888000 20922789888000
17 355687428096000 355687428096000
18 6402373705728000 6402373705728000
19 121645100408832000 121645100408832000
20 2432902008176640000 2432902008176640000
</pre>
 
=={{header|embedded C for AVR MCU}}==
=== Iterative ===
<syntaxhighlight lang="c">long factorial(int n) {
long result = 1;
do {
result *= n;
while(--n);
return result;
}</syntaxhighlight>
 
=={{header|Erlang}}==
With a fold:
<langsyntaxhighlight lang="erlang">lists:foldl(fun(X,Y) -> X*Y end, 1, lists:seq(1,N)).</langsyntaxhighlight>
 
With a recursive function:
<langsyntaxhighlight lang="erlang">fac(1) -> 1;
fac(N) -> N * fac(N-1).</langsyntaxhighlight>
 
With a tail-recursive function:
<langsyntaxhighlight lang="erlang">fac(N) -> fac(N-1,N).
fac(1,N) -> N;
fac(I,N) -> fac(I-1,N*I).</langsyntaxhighlight>
 
=={{header|ERRE}}==
Line 2,670 ⟶ 4,222:
 
'''Iterative procedure:'''
<syntaxhighlight lang="erre">
<lang ERRE>
PROCEDURE FACTORIAL(X%->F)
F=1
Line 2,679 ⟶ 4,231:
END IF
END PROCEDURE
</syntaxhighlight>
</lang>
 
'''Recursive procedure:'''
<syntaxhighlight lang="erre">
<lang ERRE>
PROCEDURE FACTORIAL(FACT,X%->FACT)
IF X%>1 THEN FACTORIAL(X%*FACT,X%-1->FACT)
END IF
END PROCEDURE
</syntaxhighlight>
</lang>
Procedure call is for example FACTORIAL(1,5->N)
 
Line 2,693 ⟶ 4,245:
Straight forward methods
===Iterative===
<langsyntaxhighlight Euphorialang="euphoria">function factorial(integer n)
atom f = 1
while n > 1 do
Line 2,701 ⟶ 4,253:
 
return f
end function</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Euphorialang="euphoria">function factorial(integer n)
if n > 1 then
return factorial(n-1) * n
Line 2,710 ⟶ 4,262:
return 1
end if
end function</langsyntaxhighlight>
 
===Tail Recursive===
{{works with|Euphoria|4.0.0}}
<langsyntaxhighlight Euphorialang="euphoria">function factorial(integer n, integer acc = 1)
if n <= 0 then
return acc
Line 2,720 ⟶ 4,272:
return factorial(n-1, n*acc)
end if
end function</langsyntaxhighlight>
 
==='Paper tape' / Virtual Machine version===
Line 2,726 ⟶ 4,278:
Another 'Paper tape' / Virtual Machine version, with as much as possible happening in the tape itself. Some command line handling as well.
 
<langsyntaxhighlight Euphorialang="euphoria">include std/mathcons.e
 
enum MUL_LLL,
Line 2,831 ⟶ 4,383:
end if
ip += 1
end while</langsyntaxhighlight>
 
=={{header|Excel}}==
Line 2,837 ⟶ 4,389:
Choose a cell and write in the function bar on the top :
 
<langsyntaxhighlight lang="excel">
=fact(5)
</syntaxhighlight>
</lang>
 
The result is shown as :
Line 2,849 ⟶ 4,401:
=={{header|Ezhil}}==
Recursive
<langsyntaxhighlight lang="src="Pythonpython"">
நிரல்பாகம் fact ( n )
@( n == 0 ) ஆனால்
Line 2,859 ⟶ 4,411:
 
பதிப்பி fact ( 10 )
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">//val inline factorial :
// ^a -> ^a
// when ^a : (static member get_One : -> ^a) and
// ^a : (static member ( + ) : ^a * ^a -> ^a) and
// ^a : (static member ( * ) : ^a * ^a -> ^a)
let inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]</langsyntaxhighlight>
<div style="width:full;overflow:scroll">
> factorial 8;;
Line 2,877 ⟶ 4,429:
=={{header|Factor}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="factor">USING: math.ranges sequences ;
 
: factorial ( n -- n ) [1,b] product ;</langsyntaxhighlight>
 
The ''[1,b]'' word takes a number from the stack and pushes a range, which is then passed to ''product''.
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[1\[$][$@*\1-]#%]f:
^'0- f;!.</langsyntaxhighlight>
Recursive:
<langsyntaxhighlight lang="false">[$1=~[$1-f;!*]?]f:</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">def class Number {
def factorial {
1 upto: self . product
Line 2,899 ⟶ 4,451:
1 upto: 10 do_each: |i| {
i to_s ++ "! = " ++ (i factorial) println
}</langsyntaxhighlight>
 
=={{header|Fantom}}==
The following uses 'Ints' to hold the computed factorials, which limits results to a 64-bit signed integer.
<langsyntaxhighlight lang="fantom">class Main
{
static Int factorialRecursive (Int n)
Line 2,938 ⟶ 4,490:
echo (factorialFunctional(20))
}
}</langsyntaxhighlight>
 
=={{header|Fermat}}==
The factorial function is built in.
<syntaxhighlight lang="fermat">666!</syntaxhighlight>
{{out}}<pre>
10106320568407814933908227081298764517575823983241454113404208073574138021 `
03697022989202806801491012040989802203557527039339704057130729302834542423840165 `
85642874066153029797241068282869939717688434251350949378748077490349338925526287 `
83417618832618994264849446571616931313803111176195730515264233203896418054108160 `
67607893067483259816815364609828668662748110385603657973284604842078094141556427 `
70874534510059882948847250594907196772727091196506088520929434066550648022642608 `
33579015030977811408324970137380791127776157191162033175421999994892271447526670 `
85796752482688850461263732284539176142365823973696764537603278769322286708855475 `
06983568164371084614056976933006577541441308350104365957229945444651724282400214 `
05551404642962910019014384146757305529649145692697340385007641405511436428361286 `
13304734147348086095123859660926788460671181469216252213374650499557831741950594 `
82714722569989641408869425126104519667256749553222882671938160611697400311264211 `
15613325735032129607297117819939038774163943817184647655275750142521290402832369 `
63922624344456975024058167368431809068544577258472983979437818072648213608650098 `
74936976105696120379126536366566469680224519996204004154443821032721047698220334 `
84585960930792965695612674094739141241321020558114937361996687885348723217053605 `
11305248710796441479213354542583576076596250213454667968837996023273163069094700 `
42946710666392541958119313633986054565867362395523193239940480940410876723200000 `
00000000000000000000000000000000000000000000000000000000000000000000000000000000 `
00000000000000000000000000000000000000000000000000000000000000000000000000000000
</pre>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">1.1 F N=0,10; D 2
1.2 S N=-3; D 2
1.3 S N=100; D 2
1.4 S N=300; D 2
1.5 Q
 
2.1 I (N)3.1,4.1
2.2 S R=1
2.3 F I=1,N; S R=R*I
2.4 T "FACTORIAL OF ", %3.0, N, " IS ", %8.0, R, !
2.9 R
 
3.1 T "N IS NEGATIVE" !; D 2.9
 
4.1 T "FACTORIAL OF 0 IS 1" !; D 2.9</syntaxhighlight>
{{output}}
<pre>
FACTORIAL OF 0 IS 1
FACTORIAL OF = 1 IS = 1
FACTORIAL OF = 2 IS = 2
FACTORIAL OF = 3 IS = 6
FACTORIAL OF = 4 IS = 24
FACTORIAL OF = 5 IS = 120
FACTORIAL OF = 6 IS = 720
FACTORIAL OF = 7 IS = 5040
FACTORIAL OF = 8 IS = 40320
FACTORIAL OF = 9 IS = 362880
FACTORIAL OF = 10 IS = 3628800
N IS NEGATIVE
FACTORIAL OF = 100 IS = 0.93325720E+158
FACTORIAL OF = 300 IS = 0.30605100E+615
</pre>
The factorial of 300 is the largest one which FOCAL can compute, 301 causes an overflow.
 
=={{header|Forth}}==
===Single Precision===
<langsyntaxhighlight lang="forth">: fac ( n -- n! ) 1 swap 1+ 1 ?do i * loop ;</langsyntaxhighlight>
===Double Precision===
On a 64 bit computer, can compute up to 33! Also does error checking. In gforth, error code -24 is "invalid numeric argument."
<langsyntaxhighlight lang="forth">: factorial ( n -- d )
dup 33 u> -24 and throw
dup 2 < IF
Line 2,959 ⟶ 4,572:
-5 factorial d.
:2: Invalid numeric argument
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
===Fortran 90===
A simple one-liner is sufficient.
<langsyntaxhighlight lang="fortran">nfactorial = PRODUCT((/(i, i=1,n)/))</langsyntaxhighlight>
 
Recursive functions were added in Fortran 90, allowing the following:
<langsyntaxhighlight lang="fortran">INTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS)
INTEGER, INTENT(IN) :: X
 
Line 2,976 ⟶ 4,589:
END IF
 
END FUNCTION RECURSIVE_FACTORIAL</langsyntaxhighlight>
 
===FORTRAN 77===
<langsyntaxhighlight lang="fortran"> INTEGER FUNCTION FACTMFACT(N)
INTEGER N,I,FACT
FACT=1
DO 10IF I=1,(N.EQ.0) GOTO 20
DO 10 FACT=FACT*I=1,N
END</lang> FACT=FACT*I
10 CONTINUE
 
20 CONTINUE
=={{header|FPr}}==
MFACT = FACT
FP-Way
RETURN
<lang fpr>fact==((1&),iota)\(1*2)& </lang>
END</syntaxhighlight>
Recursive
<lang fpr>fact==(id<=1&)->(1&);id*fact°id-1& </lang>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Function Factorial_Iterative(n As Integer) As Integer
Var result = 1
For i As Integer = 2 To n
result *= i
Next
Return result
End Function
 
Function Factorial_Recursive(n As Integer) As Integer
If n = 0 Then Return 1
Return n * Factorial_Recursive(n - 1)
End Function
 
For i As Integer = 1 To 5
Print i; " =>"; Factorial_Iterative(i)
Next
 
For i As Integer = 6 To 10
Print Using "##"; i;
Print " =>"; Factorial_Recursive(i)
Next
 
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
1 => 1
2 => 2
3 => 6
4 => 24
5 => 120
6 => 720
7 => 5040
8 => 40320
9 => 362880
10 => 3628800
</pre>
 
=={{header|friendly interactive shell}}==
Line 3,039 ⟶ 4,608:
 
===Iterative===
<langsyntaxhighlight lang="fishshell">
function factorial
set x $argv[1]
Line 3,048 ⟶ 4,617:
echo $result
end
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="fishshell">
function factorial
set x $argv[1]
Line 3,060 ⟶ 4,629:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Frink}}==
Frink has a built-in factorial operator and function that creates arbitrarily-large numbers and caches results so that subsequent calls are fast. Some notes on its implementation:
 
<lang frink>
* Factorials are calculated once and cached in memory so further recalculation is fast.
factorial[x] := x!
* There is a limit to the size of factorials that gets cached in memory. Currently this limit is 10000!. Numbers larger than this will not be cached, but re-calculated on demand.
</lang>
* When calculating a factorial within the caching limit, say, 5000!, all of the factorials smaller than this will get calculated and cached in memory.
If you want to roll your own, you could do:
* Calculations of huge factorials larger than the cache limit 10000! are calculated by a binary splitting algorithm which makes them significantly faster on Java 1.8 and later. (Did you know that Java 1.8's BigInteger calculations got drastically faster because Frink's internal algorithms were contributed to it?)
<lang frink>
* Functions that calculate binomial coefficients like binomial[m,n] are more efficient because of the use of binary splitting algorithms, especially for large numbers.
* The function factorialRatio[a, b] allows efficient calculation of the ratio of two factorials a! / b!, using a binary splitting algorithm.
<syntaxhighlight lang="frink">
// Calculate factorial with math operator
x = 5
println[x!]
 
// Calculate factorial with built-in function
println[factorial[x]]
</syntaxhighlight>
Building a factorial function with no recursion
<syntaxhighlight lang="frink">
// Build factorial function with using a range and product function.
factorial2[x] := product[1 to x]
println[factorial2[5]]
</lang>
</syntaxhighlight>
Building a factorial function with recursion
<syntaxhighlight lang="frink">
factorial3[x] :=
{
if x <= 1
return 1
else
return x * factorial3[x-1] // function calling itself
}
 
println[factorial3[5]]
</syntaxhighlight>
 
=={{header|FunL}}==
=== Procedural ===
<langsyntaxhighlight lang="funl">def factorial( n ) =
if n < 0
error( 'factorial: n should be non-negative' )
Line 3,083 ⟶ 4,678:
res *= i
 
res</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang="funl">def
factorial( (0|1) ) = 1
factorial( n )
| n > 0 = n*factorial( n - 1 )
| otherwise = error( 'factorial: n should be non-negative' )</langsyntaxhighlight>
 
=== Tail-recursive ===
<langsyntaxhighlight lang="funl">def factorial( n )
| n >= 0 =
def
Line 3,100 ⟶ 4,695:
 
fact( 1, n )
| otherwise = error( 'factorial: n should be non-negative' )</langsyntaxhighlight>
 
=== Using a library function ===
<langsyntaxhighlight lang="funl">def factorial( n )
| n >= 0 = product( 1..n )
| otherwise = error( 'factorial: n should be non-negative' )</langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 3,112 ⟶ 4,707:
=== Recursive ===
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun fact(n: int): int =
if n == 0 then 1
else n * fact(n-1)
</syntaxhighlight>
</lang>
 
== Iterative ==
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun fact(n: int): int =
loop (out = 1) = for i < n do
out * (i+1)
in out
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">
window 1, @"Factorial", ( 0, 0, 300, 550 )
include "ConsoleWindow"
 
local fn factorialIterative( n as long ) as double
dim as double f
dim as long i
 
if ( n > 1 )
f = 1
for i = 2 Toto n
f = f * i
next i next
else
f = 1
end if
end fn = f
 
local fn factorialRecursive( n as long ) as double
dim as double f
 
if ( n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
 
dim as long i
 
for i = 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next i
 
</lang>
HandleEvents
Output:
</syntaxhighlight>
{{output}}
<pre>
Iterative: 0 = 1
Line 3,205 ⟶ 4,802:
</pre>
 
=={{header|Gambas}}==
<lang Gambas>
' Task: Factorial
' Language: Gambas
' Author: Sinuhe Masan (2019)
' Function factorial iterative
Function factorial_iter(num As Integer) As Long
Dim fact As Long
Dim i As Integer
fact = 1
If num > 1 Then
For i = 2 To num
fact = fact * i
Next
Endif
Return fact
End
 
' Function factorial recursive
Function factorial_rec(num As Integer) As Long
If num <= 1 Then
Return 1
Else
Return num * factorial_rec(num - 1)
Endif
End
 
 
Public Sub Main()
Print factorial_iter(6)
Print factorial_rec(7)
End
</lang>
Output:
<pre>
720
5040
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
Factorial(5);
 
# An implementation
fact := n -> Product([1 .. n]);</langsyntaxhighlight>
 
=={{header|Genyris}}==
<langsyntaxhighlight lang="genyris">def factorial (n)
if (< n 2) 1
* n
factorial (- n 1)</langsyntaxhighlight>
 
=={{header|GML}}==
<langsyntaxhighlight GMLlang="gml">n = argument0
j = 1
for(i = 1; i <= n; i += 1)
j *= i
return j</langsyntaxhighlight>
 
=={{header|gnuplot}}==
Gnuplot has a builtin <code>!</code> factorial operator for use on integers.
<langsyntaxhighlight lang="gnuplot">set xrange [0:4.95]
set key left
plot int(x)!</langsyntaxhighlight>
 
If you wanted to write your own it can be done recursively.
 
<langsyntaxhighlight lang="gnuplot"># Using int(n) allows non-integer "n" inputs with the factorial
# calculated on int(n) in that case.
# Arranging the condition as "n>=2" avoids infinite recursion if
Line 3,292 ⟶ 4,841:
set xrange [0:4.95]
set key left
plot factorial(x)</langsyntaxhighlight>
 
=={{header|Go}}==
===Iterative===
Sequential, but at least handling big numbers:
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,318 ⟶ 4,867:
}
return r
}</langsyntaxhighlight>
===Built in, exact===
Built in function currently uses a simple divide and conquer technique. It's a step up from sequential multiplication.
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,335 ⟶ 4,884:
func main() {
fmt.Println(factorial(800))
}</langsyntaxhighlight>
===Efficient exact===
For a bigger step up, an algorithm fast enough to compute factorials of numbers up to a million or so, see [[Factorial/Go]].
===Built in, Gamma===
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,355 ⟶ 4,904:
}
fmt.Println(100, factorial(100))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,372 ⟶ 4,921:
</pre>
===Built in, Lgamma===
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,397 ⟶ 4,946:
fmt.Println(100, factorial(100))
fmt.Println(800, factorial(800))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,417 ⟶ 4,966:
=={{header|Golfscript}}==
'''Iterative''' (uses folding)
<langsyntaxhighlight lang="golfscript">{.!{1}{,{)}%{*}*}if}:fact;
5fact puts # test</langsyntaxhighlight>
or
<langsyntaxhighlight lang="golfscript">{),(;{*}*}:fact;</langsyntaxhighlight>
'''Recursive'''
<langsyntaxhighlight lang="golfscript">{.1<{;1}{.(fact*}if}:fact;</langsyntaxhighlight>
 
=={{header|GridScriptGridscript}}==
<langsyntaxhighlight lang="gridscript">
#FACTORIAL.
 
Line 3,441 ⟶ 4,990:
(11,7):GOTO 0
(13,3):PRINT
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
=== Recursive ===
A recursive closure must be ''pre-declared''.
<langsyntaxhighlight lang="groovy">def rFact
rFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger }</langsyntaxhighlight>
 
=== Iterative ===
<langsyntaxhighlight lang="groovy">def iFact = { (it > 1) ? (2..it).inject(1 as BigInteger) { i, j -> i*j } : 1 }</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">def time = { Closure c ->
def start = System.currentTimeMillis()
def result = c()
Line 3,468 ⟶ 5,018:
factList.each { printf ' %3d', it }
println()
}</langsyntaxhighlight>
 
{{out}}
Line 3,475 ⟶ 5,025:
recursive (0.0040s elapsed) 1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000
iterative (0.0060s elapsed) 1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000</pre>
 
=={{header|Guish}}==
=== Recursive ===
<syntaxhighlight lang="guish">
fact = {
if eq(@1, 0) {
return 1
} else {
return mul(@1, fact(sub(@1, 1)))
}
}
puts fact(7)
</syntaxhighlight>
 
=== Tail recursive ===
<syntaxhighlight lang="guish">
fact = {
if eq(@1, 1) {
return @2
}
return fact(sub(@1, 1), mul(@1, @2))
}
puts fact(7, 1)
</syntaxhighlight>
 
=={{header|Haskell}}==
The simplest description: factorial is the product of the numbers from 1 to n:
<langsyntaxhighlight lang="haskell">factorial n = product [1..n]</langsyntaxhighlight>
Or, using composition and omitting the argument ([https://www.haskell.org/haskellwiki/Partial_application partial application]):
<langsyntaxhighlight lang="haskell">factorial = product . enumFromTo 1</langsyntaxhighlight>
Or, written explicitly as a fold:
<langsyntaxhighlight lang="haskell">factorial n = foldl (*) 1 [1..n]</langsyntaxhighlight>
''See also: [http://www.willamette.edu/~fruehr/haskell/evolution.html The Evolution of a Haskell Programmer]''
 
Or, if you wanted to generate a list of all the factorials:
<langsyntaxhighlight lang="haskell">factorials = scanl (*) 1 [1..]</langsyntaxhighlight>
 
Or, written without library functions:
<langsyntaxhighlight lang="haskell">factorial :: Integral -> Integral
factorial 0 = 1
factorial n = n * factorial (n-1)</langsyntaxhighlight>
 
Tail-recursive, checking the negative case:
<langsyntaxhighlight lang="haskell">fac n
| n >= 0 = go 1 n
| otherwise = error "Negative factorial!"
where go acc 0 = acc
go acc n = go (acc * n) (n - 1)</langsyntaxhighlight>
 
Using postfix notation:
<langsyntaxhighlight lang="haskell">{-# LANGUAGE PostfixOperators #-}
 
(!) :: Integer -> Integer
(!) 0 = 1
(!) n = n * ((pred n-1) !)
 
main :: IO ()
main = do
print (5 !)
print ((4 !) !)</langsyntaxhighlight>
 
 
=== Binary splitting ===
The following method is more efficient for large numbers.
<syntaxhighlight lang="haskell">-- product of [a,a+1..b]
productFromTo a b =
if a>b then 1
else if a == b then a
else productFromTo a c * productFromTo (c+1) b
where c = (a+b) `div` 2
 
factorial = productFromTo 1</syntaxhighlight>
 
=={{header|Haxe}}==
===Iterative===
<langsyntaxhighlight lang="haxe">static function factorial(n:Int):Int {
var result = 1;
while (1<n)
result *= n--;
return result;
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="haxe">static function factorial(n:Int):Int {
return n == 0 ? 1 : n * factorial2(n - 1);
}</langsyntaxhighlight>
 
===Tail-Recursive===
<langsyntaxhighlight lang="haxe">inline static function _fac_aux(n, acc:Int):Int {
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
Line 3,531 ⟶ 5,119:
static function factorial(n:Int):Int {
return _fac_aux(n,1);
}</langsyntaxhighlight>
 
===Functional===
<langsyntaxhighlight lang="haxe">static function factorial(n:Int):Int {
return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);
}</langsyntaxhighlight>
 
===Comparison===
<langsyntaxhighlight lang="haxe">using StringTools;
using Lambda;
 
Line 3,596 ⟶ 5,184:
Sys.println('functional'.rpad(' ', 20) + 'result: $result time: $duration ms');
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,608 ⟶ 5,196:
=={{header|hexiscript}}==
===Iterative===
<langsyntaxhighlight lang="hexiscript">fun fac n
let acc 1
while n > 0
Line 3,614 ⟶ 5,202:
endwhile
return acc
endfun</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="hexiscript">fun fac n
if n <= 0
return 1
Line 3,622 ⟶ 5,210:
return n * fac (n - 1)
endif
endfun</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">WRITE(Clipboard) factorial(6) ! pasted: 720
 
FUNCTION factorial(n)
Line 3,632 ⟶ 5,220:
factorial = factorial * i
ENDDO
END</langsyntaxhighlight>
 
=={{header|HolyC}}==
=== Iterative ===
<langsyntaxhighlight lang="holyc">U64 Factorial(U64 n) {
U64 i, result = 1;
for (i = 1; i <= n; ++i)
Line 3,644 ⟶ 5,232:
 
Print("1: %d\n", Factorial(1));
Print("10: %d\n", Factorial(10));</langsyntaxhighlight>
 
Note: Does not support negative numbers.
 
=== Recursive ===
<langsyntaxhighlight lang="holyc">I64 Factorial(I64 n) {
if (n == 0)
return 1;
Line 3,659 ⟶ 5,247:
Print("+1: %d\n", Factorial(1));
Print("+10: %d\n", Factorial(10));
Print("-10: %d\n", Factorial(-10));</langsyntaxhighlight>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="clojure">(defn ! [n]
(reduce *
(range 1 (inc n))
Line 3,668 ⟶ 5,256:
 
(print (! 6)) ; 720
(print (! 0)) ; 1</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">concept factorial(n) {
return n!
}
Line 3,683 ⟶ 5,271:
print(factorial(22))
}
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
===Recursive===
<langsyntaxhighlight Iconlang="icon">procedure factorial(n)
n := integer(n) | runerr(101, n)
if n < 0 then fail
return if n = 0 then 1 else n*factorial(n-1)
end </langsyntaxhighlight>
===Iterative===
The {{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/src/procs/factors.icn factors] provides the following iterative procedure which can be included with 'link factors':
<langsyntaxhighlight Iconlang="icon">procedure factorial(n) #: return n! (n factorial)
local i
n := integer(n) | runerr(101, n)
Line 3,701 ⟶ 5,289:
every i *:= 1 to n
return i
end</langsyntaxhighlight>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">function fact,n
return, product(lindgen(n)+1)
end</langsyntaxhighlight>
 
=={{header|Inform 6}}==
<langsyntaxhighlight lang="inform6">[ factorial n;
if (n == 0)
return 1;
else
return n * factorial(n - 1);
];</langsyntaxhighlight>
 
=={{header|Insitux}}==
 
{{trans|Clojure}}
 
'''Iterative'''
 
<syntaxhighlight lang="insitux">
(function factorial n
(... *1 (range 2 (inc n))))
</syntaxhighlight>
 
'''Recursive'''
 
<syntaxhighlight lang="insitux">
(function factorial x
(if (< x 2)
1
(*1 x (factorial (dec x)))))
</syntaxhighlight>
 
=={{header|Io}}==
Factorials are built-in to Io:
<syntaxhighlight lang ="io">3 factorial</langsyntaxhighlight>
 
=={{header|J}}==
=== Operator ===
<langsyntaxhighlight lang="j"> ! 8 NB. Built in factorial operator
40320</langsyntaxhighlight>
=== Iterative / Functional ===
<langsyntaxhighlight lang="j"> */1+i.8
40320</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="j"> (*$:@:<:)^:(1&<) 8
40320</langsyntaxhighlight>
 
=== Generalization ===
Factorial, like most of J's primitives, is generalized (mathematical generalization is often something to avoid in application code while being something of a curated virtue in utility code):
<div style="width:full;overflow:scroll">
<langsyntaxhighlight lang="j"> ! 8 0.8 _0.8 NB. Generalizes as 1 + the gamma function
40320 0.931384 4.59084
! 800x NB. Also arbitrarily large
7710530113353860041446393977750283605955564018160102391634109940339708518270930693670907697955390330926478612242306774446597851526397454014801846531749097625044706382742591201733097017026108750929188168469858421505936237186038616420630788341172340985137252...</langsyntaxhighlight>
</div>
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn factorial(anon n: i64) throws -> i64 {
if n < 0 {
throw Error::from_string_literal("Factorial's operand must be non-negative")
}
mut result = 1
for i in 1..(n + 1) {
result *= i
}
return result
}
 
fn main() {
for i in 0..11 {
println("{} factorial is {}", i, factorial(i))
}
}
</syntaxhighlight>
 
=={{header|Janet}}==
===Recursive===
====Non-Tail Recursive====
<syntaxhighlight lang="janet">
(defn factorial [x]
(cond
(< x 0) nil
(= x 0) 1
(* x (factorial (dec x)))))
</syntaxhighlight>
 
====Tail Recursive====
Given the initial recursive sample is not using tail recursion, there is a possibility to hit a stack overflow (if the user has lowered Janet's very high default max stack size) or exhaust the host's available memory.
 
The recursive sample can be written with tail recursion (Janet supports TCO) to perform the algorithm in linear time and constant space, instead of linear space.
<syntaxhighlight lang="janet">
(defn factorial-iter [product counter max-count]
(if (> counter max-count)
product
(factorial-iter (* counter product) (inc counter) max-count)))
 
(defn factorial [n]
(factorial-iter 1 1 n))
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="janet">
(defn factorial [x]
(cond
(< x 0) nil
(= x 0) 1
(do
(var fac 1)
(for i 1 (inc x)
(*= fac i))
fac)))
</syntaxhighlight>
 
===Functional===
<syntaxhighlight lang="janet">
(defn factorial [x]
(cond
(< x 0) nil
(= x 0) 1
(product (range 1 (inc x)))))
</syntaxhighlight>
 
=={{header|Java}}==
===Iterative===
<langsyntaxhighlight lang="java5">
package programas;
 
Line 3,797 ⟶ 5,472:
}
 
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="java5">
package programas;
 
Line 3,858 ⟶ 5,533:
}
 
</syntaxhighlight>
</lang>
 
===Simplified and Combined Version===
<syntaxhighlight lang="java 12">
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class LargeFactorial {
public static long userInput;
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Input factorial integer base: ");
try {
userInput = input.nextLong();
System.out.println(userInput + "! is\n" + factorial(userInput) + " using standard factorial method.");
System.out.println(userInput + "! is\n" + factorialRec(userInput) + " using recursion method.");
}catch(InputMismatchException x){
System.out.println("Please give integral numbers.");
}catch(StackOverflowError ex){
if(userInput > 0) {
System.out.println("Number too big.");
}else{
System.out.println("Please give non-negative(positive) numbers.");
}
}finally {
System.exit(0);
}
}
public static BigInteger factorialRec(long n){
BigInteger result = BigInteger.ONE;
return n == 0 ? result : result.multiply(BigInteger.valueOf(n)).multiply(factorial(n-1));
}
public static BigInteger factorial(long n){
BigInteger result = BigInteger.ONE;
for(int i = 1; i <= n; i++){
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,864 ⟶ 5,580:
===Iterative===
 
<langsyntaxhighlight lang="javascript">function factorial(n) {
//check our edge case
if (n < 0) { throw "Number must be non-negative"; }
Line 3,875 ⟶ 5,591:
}
return result;
}</langsyntaxhighlight>
 
===Recursive===
Line 3,881 ⟶ 5,597:
====ES5 (memoized )====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function(x) {
 
var memo = {};
Line 3,891 ⟶ 5,607:
return factorial(x);
})(18);</langsyntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang JavaScript="javascript">6402373705728000</langsyntaxhighlight>
 
Or, assuming that we have some sort of integer range function, we can memoize using the accumulator of a fold/reduce:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,925 ⟶ 5,641:
return factorial(18);
 
})();</langsyntaxhighlight>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">6402373705728000</langsyntaxhighlight>
 
 
====ES6====
<langsyntaxhighlight lang="javascript">var factorial = n => (n < 2) ? 1 : n * factorial(n - 1);</langsyntaxhighlight>
 
 
Or, as an alternative to recursion, we can fold/reduce a product function over the range of integers 1..n
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,964 ⟶ 5,680:
// MAIN ------
return test();
})();</langsyntaxhighlight>
{{Out}}
<pre>6402373705728000</pre>
 
 
 
The first part outputs the factorial for every addition to the array and the second part calculates factorial from a single number.
 
<syntaxhighlight lang="javascript">
<html>
 
<body>
 
<button onclick="incrementFact()">Factorial</button>
<p id="FactArray"></p>
<p id="Factorial"></p>
<br>
</body>
 
</html>
 
<input id="userInput" value="">
<br>
<button onclick="singleFact()">Single Value Factorial</button>
<p id="SingleFactArray"></p>
<p id="SingleFactorial"></p>
 
 
<script>
function mathFact(total, sum) {
return total * sum;
}
 
var incNumbers = [1];
 
function incrementFact() {
var n = incNumbers.pop();
incNumbers.push(n);
incNumbers.push(n + 1);
document.getElementById("FactArray").innerHTML = incNumbers;
document.getElementById("Factorial").innerHTML = incNumbers.reduceRight(mathFact);
 
}
 
var singleNum = [];
 
function singleFact() {
var x = document.getElementById("userInput").value;
for (i = 0; i < x; i++) {
singleNum.push(i + 1);
document.getElementById("SingleFactArray").innerHTML = singleNum;
}
document.getElementById("SingleFactorial").innerHTML = singleNum.reduceRight(mathFact);
singleNum = [];
}
 
</script></syntaxhighlight>
 
=={{header|JOVIAL}}==
<langsyntaxhighlight JOVIALlang="jovial">PROC FACTORIAL(ARG) U;
BEGIN
ITEM ARG U;
Line 3,977 ⟶ 5,748:
TEMP = TEMP*I;
FACTORIAL = TEMP;
END</langsyntaxhighlight>
 
=={{header|Joy}}==
<<syntaxhighlight lang Joy="joy">DEFINE factorial! == [0 =] [pop 1] [dup 1 - factorial *] ifteprimrec. </lang>
6!.
</syntaxhighlight>
 
=={{header|jq}}==
An efficient and idiomatic definition in jq is simply to multiply the first n integers:<langsyntaxhighlight lang="jq">def fact:
reduce range(1; .+1) as $i (1; . * $i);</langsyntaxhighlight>
Here is a rendition in jq of the standard recursive definition of the factorial function, assuming n is non-negative: <langsyntaxhighlight lang="jq">def fact(n):
if n <= 1 then n
else n * fact(n-1)
end;
</langsyntaxhighlight>Recent versions of jq support tail recursion optimization for 0-arity filters, so here is an implementation that would would benefit from this optimization. The helper function, <tt>_fact</tt>, is defined here as a subfunction of the main function, which is a filter that accepts the value of n from its input.<langsyntaxhighlight lang="jq">def fact:
def _fact:
# Input: [accumulator, counter]
Line 3,996 ⟶ 5,769:
end;
# Extract the accumulated value from the output of _fact:
[1, .] | _fact | .[0] ;</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Factorial, in Jsish */
 
/* recursive */
Line 4,020 ⟶ 5,793:
;factorial(42);
try { factorial(-1); } catch (err) { puts(err); }
}</langsyntaxhighlight>
 
{{out}}
Line 4,058 ⟶ 5,831:
 
'''Dynamic version''':
<langsyntaxhighlight lang="julia">function fact(n::Integer)
n < 0 && return zero(n)
f = one(n)
Line 4,069 ⟶ 5,842:
for i in 10:20
println("$i -> ", fact(i))
end</langsyntaxhighlight>
 
{{out}}
Line 4,085 ⟶ 5,858:
 
'''Alternative version''':
<langsyntaxhighlight lang="julia">fact2(n::Integer) = prod(Base.OneTo(n))
@show fact2(20)</langsyntaxhighlight>
{{out}}
<pre>fact2(20) = 2432902008176640000</pre>
Line 4,092 ⟶ 5,865:
=={{header|K}}==
===Iterative===
<langsyntaxhighlight Klang="k"> facti:*/1+!:
facti 5
120</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight Klang="k"> factr:{:[x>1;x*_f x-1;1]}
factr 6
720</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">{ recursive }
:factorial
dup 1 great (
[dup 1 - factorial *]
[drop 1]
) if
;
{ iterative }
:factorial2
1 swap [*] for
;
( 0 22 ) [
"Factorial(" print dup print ") = " print factorial2 print nl
] for
 
" " input</syntaxhighlight>
{{out}}
<pre>Factorial(0) = 1
Factorial(1) = 1
Factorial(2) = 2
Factorial(3) = 6
Factorial(4) = 24
Factorial(5) = 120
Factorial(6) = 720
Factorial(7) = 5040
Factorial(8) = 40320
Factorial(9) = 362880
Factorial(10) = 3628800
Factorial(11) = 39916800
Factorial(12) = 479001600
Factorial(13) = 6.22703e+9
Factorial(14) = 8.71783e+10
Factorial(15) = 1.30768e+12
Factorial(16) = 2.09228e+13
Factorial(17) = 3.55688e+14
Factorial(18) = 6.40238e+15
Factorial(19) = 1.21646e+17
Factorial(20) = 2.4329e+18
Factorial(21) = 5.1091e+19
Factorial(22) = 1.124e+21</pre>
 
=={{header|Klong}}==
Based on the K examples above.
<syntaxhighlight lang="k">
<lang k>
factRecursive::{:[x>1;x*.f(x-1);1]}
factIterative::{*/1+!x}
</syntaxhighlight>
</lang>
 
=={{header|KonsolScript}}==
<langsyntaxhighlight KonsolScriptlang="konsolscript">function factorial(Number n):Number {
Var:Number ret;
if (n >= 0) {
Line 4,120 ⟶ 5,937:
}
return ret;
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun facti(n: Int) = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
Line 4,142 ⟶ 5,959:
println("$n! = " + facti(n))
println("$n! = " + factr(n))
}</langsyntaxhighlight>
{{Out}}
<pre>20! = 2432902008176640000
20! = 2432902008176640000</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def fac
{lambda {:n}
{if {< :n 1}
then 1
else {long_mult :n {fac {- :n 1}}}}}}
 
{fac 6}
-> 720
 
{fac 100}
-> 93326215443944152681699238856266700490715968264381621468592963895217599993229
915608941463976156518286253697920827223758251185210916864000000000000000000000000
</syntaxhighlight>
 
=={{header|Lang}}==
===Iterative===
<syntaxhighlight lang="lang">
fp.fact = ($n) -> {
if($n < 0) {
throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)
}
$ret = 1L
$i = 2
while($i <= $n) {
$ret *= $i
$i += 1
}
return $ret
}
</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="lang">
fp.fact = ($n) -> {
if($n < 0) {
throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)
}elif($n < 2) {
return 1L
}
return parser.op($n * fp.fact(-|$n))
}
</syntaxhighlight>
 
===Array Reduce===
<syntaxhighlight lang="lang">
fp.fact = ($n) -> {
if($n < 0) {
throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)
}
return fn.arrayReduce(fn.arrayGenerateFrom(fn.inc, $n), 1L, fn.mul)
}
</syntaxhighlight>
 
=={{header|Lang5}}==
===Folding===
<langsyntaxhighlight lang="lang5"> : fact iota 1 + '* reduce ;
5 fact
120
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="lang5">
: fact dup 2 < if else dup 1 - fact * then ;
5 fact
120
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
=== Folding ===
<langsyntaxhighlight lang="langur">val .factorial = ffn(.n) fold(ffn{*}, .x x2 .y, pseries. .n)
writeln .factorial(7)</langsyntaxhighlight>
 
{{works with|langur|0.6.6}}
<lang langur>val .factorial = f fold(f{x}, pseries .n)
writeln .factorial(7)</lang>
 
{{works with|langur|0.6.13}}
<lang langur>val .factorial = f fold(f{x}, 2 to .n)
writeln .factorial(7)</lang>
 
=== Recursive ===
<langsyntaxhighlight lang="langur">val .factorial = ffn(.x) { if(.x < 2: 1; .x x* self(.x - 1)) }
writeln .factorial(7)</langsyntaxhighlight>
 
=== Iterative ===
<langsyntaxhighlight lang="langur">val .factorial = ffn(.i) {
var .answer = 1
for .x in 2 to.. .i {
.answer x*= .x
}
.answer
}
 
writeln .factorial(7)</lang>
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative Folding ===
<langsyntaxhighlight lang="langur">val .factorial = ffn(.n) { for[=1] .x in .n { _for x*= .x } }
writeln .factorial(7)</langsyntaxhighlight>
 
{{out}}
Line 4,197 ⟶ 6,068:
=={{header|Lasso}}==
===Iterative===
<langsyntaxhighlight lang="lasso">define factorial(n) => {
local(x = 1)
with i in generateSeries(2, #n)
Line 4,204 ⟶ 6,075:
}
return #x
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="lasso">define factorial(n) => #n < 2 ? 1 | #n * factorial(#n - 1)</langsyntaxhighlight>
 
=={{header|Latitude}}==
 
===Functional===
<langsyntaxhighlight lang="latitude">factorial := {
1 upto ($1 + 1) product.
}.</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="latitude">factorial := {
takes '[n].
if { n == 0. } then {
Line 4,224 ⟶ 6,095:
n * factorial (n - 1).
}.
}.</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="latitude">factorial := {
local 'acc = 1.
1 upto ($1 + 1) do {
Line 4,233 ⟶ 6,104:
}.
acc.
}.</langsyntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
n is number
 
procedure:
sub factorial
parameters:
n is number
result is number
local data:
i is number
m is number
procedure:
store 1 in result
in m solve n + 1
for i from 1 to m step 1 do
multiply result by i in result
repeat
end sub
create statement "get factorial of $ in $" executing factorial
 
get factorial of 5 in n
display n lf
</syntaxhighlight>
{{out}}
<pre>
120
</pre>
 
=={{header|Lean}}==
 
<syntaxhighlight lang="lean">
def factorial (n : Nat) : Nat :=
match n with
| 0 => 1
| (k + 1) => (k + 1) * factorial (k)
</syntaxhighlight>
 
=={{header|LFE}}==
Line 4,242 ⟶ 6,151:
 
''Using the'' <tt>cond</tt> ''form'':
<langsyntaxhighlight lang="lisp">
(defun factorial (n)
(cond
((== n 0) 1)
((> n 0) (* n (factorial (- n 1))))))
</syntaxhighlight>
</lang>
 
''Using guards (with the'' <tt>when</tt> ''form)'':
<langsyntaxhighlight lang="lisp">
(defun factorial
((n) (when (== n 0)) 1)
((n) (when (> n 0))
(* n (factorial (- n 1)))))
</syntaxhighlight>
</lang>
 
''Using pattern matching and a guard'':
<langsyntaxhighlight lang="lisp">
(defun factorial
((0) 1)
((n) (when (> n 0))
(* n (factorial (- n 1)))))
</syntaxhighlight>
</lang>
 
===Tail-Recursive Version===
 
<langsyntaxhighlight lang="lisp">
(defun factorial (n)
(factorial n 1))
Line 4,275 ⟶ 6,184:
((n acc) (when (> n 0))
(factorial (- n 1) (* n acc))))
</syntaxhighlight>
</lang>
 
Example usage in the REPL:
<langsyntaxhighlight lang="lisp">
> (lists:map #'factorial/1 (lists:seq 10 20))
(3628800
Line 4,291 ⟶ 6,200:
121645100408832000
2432902008176640000)
</syntaxhighlight>
</lang>
 
Or, using <tt>io:format</tt> to print results to <tt>stdout</tt>:
<langsyntaxhighlight lang="lisp">
> (lists:foreach
(lambda (x)
Line 4,311 ⟶ 6,220:
2432902008176640000
ok
</syntaxhighlight>
</lang>
 
Note that the use of <tt>progn</tt> above was simply to avoid the list of <tt>ok</tt>s that are generated as a result of calling <tt>io:format</tt> inside a <tt>lists:map</tt>'s anonymous function.
 
=={{header|Liberty BASIC}}==
<lang lb> for i =0 to 40
print " FactorialI( "; using( "####", i); ") = "; factorialI( i)
print " FactorialR( "; using( "####", i); ") = "; factorialR( i)
next i
 
wait
 
function factorialI( n)
if n >1 then
f =1
For i = 2 To n
f = f * i
Next i
else
f =1
end if
factorialI =f
end function
 
function factorialR( n)
if n <2 then
f =1
else
f =n *factorialR( n -1)
end if
factorialR =f
end function
 
end</lang>
 
=={{header|Lingo}}==
===Recursive===
<langsyntaxhighlight lang="lingo">on fact (n)
if n<=1 then return 1
return n * fact(n-1)
end</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="lingo">on fact (n)
res = 1
repeat with i = 2 to n
Line 4,360 ⟶ 6,238:
end repeat
return res
end</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">- factorial x : INTEGER : INTEGER <- (
+ result : INTEGER;
(x <= 1).if {
Line 4,371 ⟶ 6,249:
};
result
);</langsyntaxhighlight>
 
=={{header|Little Man Computer}}==
The Little Man can cope with integers up to 999. So he can calculate up to 6 factorial before it all gets too much for him.
<syntaxhighlight lang="little man computer">
// Little Man Computer
// Reads an integer n and prints n factorial
// Works for n = 0..6
LDA one // initialize factorial to 1
STA fac
INP // get n from user
BRZ done // if n = 0, return 1
STA n // else store n
LDA one // initialize k = 1
outer STA k // outer loop: store latest k
LDA n // test for k = n
SUB k
BRZ done // done if so
LDA fac // save previous factorial
STA prev
LDA k // initialize i = k
inner STA i // inner loop: store latest i
LDA fac // build factorial by repeated addition
ADD prev
STA fac
LDA i // decrement i
SUB one
BRZ next_k // if i = 0, move on to next k
BRA inner // else loop for another addition
next_k LDA k // increment k
ADD one
BRA outer // back to start of outer loop
done LDA fac // done, load the result
OUT // print it
HLT // halt
n DAT 0 // input value
k DAT 0 // outer loop counter, 1 up to n
i DAT 0 // inner loop counter, k down to 0
fac DAT 0 // holds k!, i.e. n! when done
prev DAT 0 // previous value of fac
one DAT 1 // constant 1
// end
</syntaxhighlight>
 
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">// recursive
function factorialr n
if n < 2 then
Line 4,398 ⟶ 6,319:
// iterative
function factorialit n
put 1 into f
if n > 1 then
repeat with i = 1 to n
Line 4,405 ⟶ 6,326:
end if
return f
end factorialit</langsyntaxhighlight>
 
=={{header|LLVM}}==
<langsyntaxhighlight lang="llvm">; ModuleID = 'factorial.c'
; source_filename = "factorial.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 4,487 ⟶ 6,408:
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</langsyntaxhighlight>
{{out}}
<pre>120</pre>
Line 4,494 ⟶ 6,415:
===Recursive===
 
<langsyntaxhighlight lang="logo">to factorial :n
if :n < 2 [output 1]
output :n * factorial :n-1
end</langsyntaxhighlight>
 
===Iterative===
Line 4,503 ⟶ 6,424:
NOTE: Slight code modifications may needed in order to run this as each Logo implementation differs in various ways.
 
<langsyntaxhighlight lang="logo">to factorial :n
make "fact 1
make "i 1
repeat :n [make "fact :fact * :i make "i :i + 1]
print :fact
end</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
<langsyntaxhighlight lang="lolcode">HAI 1.3
 
HOW IZ I Faktorial YR Number
Line 4,526 ⟶ 6,447:
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR Loop
KTHXBYE</langsyntaxhighlight>
{{Out}}
<pre>0! = 1
Line 4,544 ⟶ 6,465:
=={{header|Lua}}==
===Recursive===
<langsyntaxhighlight lang="lua">function fact(n)
return n > 0 and n * fact(n-1) or 1
end</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="lua">function fact(n, acc)
acc = acc or 1
if n == 0 then
Line 4,554 ⟶ 6,475:
end
return fact(n-1, n*acc)
end</langsyntaxhighlight>
===Memoization===
The memoization table can be accessed directly (eg. <code>fact[10]</code>) and will return the memoized value,
Line 4,560 ⟶ 6,481:
 
If called as a function (eg. <code>fact(10)</code>), the value will be calculated, memoized and returned.
<langsyntaxhighlight Lualang="lua">fact = setmetatable({[0] = 1}, {
__call = function(t,n)
if n < 0 then return 0 end
Line 4,566 ⟶ 6,487:
return t[n]
end
})</langsyntaxhighlight>
 
 
=={{header|M2000 Interpreter}}==
Line 4,578 ⟶ 6,498:
1@ is 1 in Decimal type (27 digits).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Locale 1033 ' ensure #,### print with comma
Line 4,601 ⟶ 6,521:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 4,634 ⟶ 6,554:
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`factorial',`ifelse(`$1',0,1,`eval($1*factorial(decr($1)))')')dnl
dnl
factorial(5)</langsyntaxhighlight>
 
{{out}}
<pre>
120
</pre>
 
=={{header|MAD}}==
 
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
R CALCULATE FACTORIAL OF N
INTERNAL FUNCTION(N)
ENTRY TO FACT.
RES = 1
THROUGH FACMUL, FOR MUL = 2, 1, MUL.G.N
FACMUL RES = RES * MUL
FUNCTION RETURN RES
END OF FUNCTION
R USE THE FUNCTION TO PRINT 0! THROUGH 12!
VECTOR VALUES FMT = $I2,6H ! IS ,I9*$
THROUGH PRNFAC, FOR NUM = 0, 1, NUM.G.12
PRNFAC PRINT FORMAT FMT, NUM, FACT.(NUM)
 
END OF PROGRAM</syntaxhighlight>
 
{{out}}
 
<pre> 0! IS 1
1! IS 1
2! IS 2
3! IS 6
4! IS 24
5! IS 120
6! IS 720
7! IS 5040
8! IS 40320
9! IS 362880
10! IS 3628800
11! IS 39916800
12! IS 479001600
</pre>
 
Line 4,646 ⟶ 6,603:
 
Recursive version, MANOOLish &ldquo;cascading&rdquo; notation:
<syntaxhighlight lang="manool">
<lang MANOOL>
{ let rec
{ Fact = -- compile-time constant binding
Line 4,657 ⟶ 6,614:
Fact
}
</syntaxhighlight>
</lang>
 
Conventional notation (equivalent to the above up to AST):
<syntaxhighlight lang="manool">
<lang MANOOL>
{ let rec
{ Fact = -- compile-time constant binding
Line 4,672 ⟶ 6,629:
Fact
}
</syntaxhighlight>
</lang>
 
Iterative version (in MANOOL, probably more appropriate in this particular case):
<syntaxhighlight lang="manool">
<lang MANOOL>
{ let
{ Fact = -- compile-time constant binding
Line 4,688 ⟶ 6,645:
Fact
}
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Builtin
<syntaxhighlight lang="maple">
<lang Maple>
> 5!;
120
</syntaxhighlight>
</lang>
Recursive
<langsyntaxhighlight Maplelang="maple">RecFact := proc( n :: nonnegint )
if n = 0 or n = 1 then
1
Line 4,704 ⟶ 6,661:
end if
end proc:
</syntaxhighlight>
</lang>
<syntaxhighlight lang="maple">
<lang Maple>
> seq( RecFact( i ) = i!, i = 0 .. 10 );
1 = 1, 1 = 1, 2 = 2, 6 = 6, 24 = 24, 120 = 120, 720 = 720, 5040 = 5040,
 
40320 = 40320, 362880 = 362880, 3628800 = 3628800
</syntaxhighlight>
</lang>
Iterative
<syntaxhighlight lang="maple">
<lang Maple>
IterFact := proc( n :: nonnegint )
local i;
mul( i, i = 2 .. n )
end proc:
</syntaxhighlight>
</lang>
<syntaxhighlight lang="maple">
<lang Maple>
> seq( IterFact( i ) = i!, i = 0 .. 10 );
1 = 1, 1 = 1, 2 = 2, 6 = 6, 24 = 24, 120 = 120, 720 = 720, 5040 = 5040,
 
40320 = 40320, 362880 = 362880, 3628800 = 3628800
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Note that Mathematica already comes with a factorial function, which can be used as e.g. <tt>5!</tt> (gives 120). So the following implementations are only of pedagogical value.
=== Recursive ===
<langsyntaxhighlight lang="mathematica">factorial[n_Integer] := n*factorial[n-1]
factorial[0] = 1</langsyntaxhighlight>
=== Iterative (direct loop) ===
<langsyntaxhighlight lang="mathematica">factorial[n_Integer] :=
Block[{i, result = 1}, For[i = 1, i <= n, ++i, result *= i]; result]</langsyntaxhighlight>
=== Iterative (list) ===
<langsyntaxhighlight lang="mathematica">factorial[n_Integer] := Block[{i}, Times @@ Table[i, {i, n}]]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
=== Built-in ===
The factorial function is built-in to MATLAB. The built-in function is only accurate for N <= 21 due to the precision limitations of floating point numbers.
<langsyntaxhighlight lang="matlab">answer = factorial(N)</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="matlab">function f=fac(n)
if n==0
f=1;
Line 4,747 ⟶ 6,704:
else
f=n*fac(n-1);
end</langsyntaxhighlight>
=== Iterative ===
A possible iterative solution:
<langsyntaxhighlight lang="matlab"> function b=factorial(a)
b=1;
for i=1:a
b=b*i;
end</langsyntaxhighlight>
 
=={{header|Maude}}==
<syntaxhighlight lang="maude">
<lang Maude>
fmod FACTORIAL is
 
Line 4,773 ⟶ 6,730:
 
red 11 ! .
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
=== Built-in ===
<syntaxhighlight lang ="maxima">n!</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="maxima">fact(n) := if n < 2 then 1 else n * fact(n - 1)$</langsyntaxhighlight>
=== Iterative===
<langsyntaxhighlight lang="maxima">fact2(n) := block([r: 1], for i thru n do r: r * i, r)$</langsyntaxhighlight>
 
=={{header|MAXScript}}==
=== Iterative ===
<langsyntaxhighlight lang="maxscript">fn factorial n =
(
if n == 0 then return 1
Line 4,794 ⟶ 6,751:
)
fac
)</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="maxscript">fn factorial_rec n =
(
local fac = 1
Line 4,804 ⟶ 6,761:
)
fac
)</langsyntaxhighlight>
 
=={{header|Mercury}}==
=== Recursive (using arbitrary large integers and memoisation) ===
<langsyntaxhighlight Mercurylang="mercury">:- module factorial.
 
:- interface.
Line 4,823 ⟶ 6,780:
-> integer(1)
; factorial(N - integer(1)) * N
).</langsyntaxhighlight>
 
A small test program:
<langsyntaxhighlight Mercurylang="mercury">:- module test_factorial.
:- interface.
:- import_module io.
Line 4,843 ⟶ 6,800:
Result = factorial(Number),
Fmt = integer.to_string,
io.format("factorial(%s) = %s\n", [s(Fmt(Number)), s(Fmt(Result))], !IO).</langsyntaxhighlight>
 
Example output:
<langsyntaxhighlight Bashlang="bash">factorial(100) = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</langsyntaxhighlight>
 
=={{header|Microsoft Small Basicmin}}==
{{works with|min|0.19.6}}
<lang smallbasic>'Factorial - smallbasic - 05/01/2019
<syntaxhighlight lang="min">((dup 0 ==) 'succ (dup pred) '* linrec) :factorial</syntaxhighlight>
For n = 1 To 25
f = 1
For i = 1 To n
f = f * i
EndFor
TextWindow.WriteLine("Factorial(" + n + ")=" + f)
EndFor</lang>
{{out}}
<pre>
Factorial(25)=15511210043330985984000000
</pre>
 
=={{header|MiniScript}}==
=== Iterative ===
<langsyntaxhighlight MiniScriptlang="miniscript">factorial = function(n)
result = 1
for i in range(2,n)
Line 4,872 ⟶ 6,819:
end function
 
print factorial(10)</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight MiniScriptlang="miniscript">factorial = function(n)
if n <= 0 then return 1 else return n * factorial(n-1)
end function
 
print factorial(10)</langsyntaxhighlight>
{{out}}
<pre>3628800</pre>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">var int: factorial(int: n) =
let {
array[0..n] of var int: factorial;
constraint forall(a in 0..n)(
factorial[a] == if (a == 0) then
1
else
a*factorial[a-1]
endif
)} in factorial[n];
 
var int: fac = factorial(6);
solve satisfy;
output [show(fac),"\n"];</syntaxhighlight>
=={{header|MIPS Assembly}}==
=== Iterative ===
<langsyntaxhighlight lang="mips">
##################################
# Factorial; iterative #
Line 4,934 ⟶ 6,895:
li $v0, 10 #set syscall arg to EXIT
syscall #make the syscall
</syntaxhighlight>
</lang>
=== Recursive ===
<langsyntaxhighlight lang="mips">
#reference code
#int factorialRec(int n){
Line 4,979 ⟶ 6,940:
mul $v0, $a0, $v0
jr $ra
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def factorial_iterative(n:int)
2.upto(n-1) do |i|
n *= i
Line 4,989 ⟶ 6,950:
end
 
puts factorial_iterative 10</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
Line 4,998 ⟶ 6,959:
=={{header|ML/I}}==
===Iterative===
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Factorial - iterative
MCSKIP MT,<>
Line 5,014 ⟶ 6,975:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Factorial - recursive
MCSKIP MT,<>
Line 5,028 ⟶ 6,989:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Factorial;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 5,056 ⟶ 7,017:
 
ReadChar
END Factorial.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
===Iterative===
<langsyntaxhighlight lang="modula3">PROCEDURE FactIter(n: CARDINAL): CARDINAL =
VAR
result := n;
Line 5,070 ⟶ 7,031:
END;
RETURN result;
END FactIter;</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="modula3">PROCEDURE FactRec(n: CARDINAL): CARDINAL =
VAR result := 1;
 
Line 5,080 ⟶ 7,041:
END;
RETURN result;
END FactRec;</langsyntaxhighlight>
 
=={{header|Mouse}}==
===Mouse 79===
<syntaxhighlight lang="mouse">
"PRIME NUMBERS!" N1 = (NN. 1 + = #P,N.; )
 
$P F1 = N1 =
( FF . 1 + = %AF. - ^ %AF./F. * %A - 1 + [N0 = 0 ^ ] )
N. [ %A! "!" ] @
 
$$
</syntaxhighlight>
 
=={{header|MUMPS}}==
===Iterative===
<langsyntaxhighlight MUMPSlang="mumps">factorial(num) New ii,result
If num<0 Quit "Negative number"
If num["." Quit "Not an integer"
Line 5,096 ⟶ 7,069:
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative number
Write $$factorial(3.7) ; Not an integer</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight MUMPSlang="mumps">factorial(num) ;
If num<0 Quit "Negative number"
If num["." Quit "Not an integer"
Line 5,111 ⟶ 7,084:
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative number
Write $$factorial(3.7) ; Not an integer</langsyntaxhighlight>
 
=={{header|MyrtleScript}}==
<langsyntaxhighlight MyrtleScriptlang="myrtlescript">func factorial args: int a : returns: int {
int factorial = a
repeat int i = (a - 1) : i == 0 : i-- {
Line 5,120 ⟶ 7,093:
}
return factorial
}</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def factorial(n)
result = 1
for i in range(1, n)
Line 5,130 ⟶ 7,103:
end
return result
end</langsyntaxhighlight>
 
=={{header|Neko}}==
<langsyntaxhighlight lang="neko">var factorial = function(number) {
var i = 1;
var result = 1;
Line 5,145 ⟶ 7,118:
};
 
$print(factorial(10));</langsyntaxhighlight>
 
=={{header|Nemerle}}==
Line 5,151 ⟶ 7,124:
Using '''long''', we can only use '''number <= 20''', I just don't like the scientific notation output from using a '''double'''.
Note that in the iterative example, variables whose values change are explicitly defined as mutable; the default in Nemerle is immutable values, encouraging a more functional approach.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 5,185 ⟶ 7,158:
accumulator //implicit return
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 5,238 ⟶ 7,211:
fact = 1
 
return fact</langsyntaxhighlight>
{{out}}
<pre>
Line 5,248 ⟶ 7,221:
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">> (define (factorial n) (exp (gammaln (+ n 1))))
(lambda (n) (exp (gammaln (+ n 1))))
> (factorial 4)
24</langsyntaxhighlight>
 
=={{header|Nial}}==
(from Nial help file)
<langsyntaxhighlight lang="nial">fact is recur [ 0 =, 1 first, pass, product, -1 +]</langsyntaxhighlight>
Using it
<langsyntaxhighlight lang="nial">|fact 4
=24</langsyntaxhighlight>
 
=={{header|Nickle}}==
Factorial is a built-in operator in Nickle. To more correctly satisfy the task, it is wrapped in a function here, but does not need to be. Inputs of 1 or below, return 1.
 
<langsyntaxhighlight lang="c">int fact(int n) { return n!; }</langsyntaxhighlight>
{{out}}
<pre>prompt$ nickle
Line 5,283 ⟶ 7,256:
=={{header|Nim}}==
===Library===
<langsyntaxhighlight lang="nim">
import math
let i:int = fac(x)
</syntaxhighlight>
</lang>
===Recursive===
<langsyntaxhighlight lang="nim">proc factorial(x): int =
if x > 0: x * factorial(x - 1)
else: 1</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="nim">proc factorial(x: int): int =
result = 1
for i in 2..x:
result *= i</langsyntaxhighlight>
 
=={{header|Niue}}==
===Recursive===
<langsyntaxhighlight Niuelang="niue">[ dup 1 > [ dup 1 - factorial * ] when ] 'factorial ;
 
( test )
4 factorial . ( => 24 )
10 factorial . ( => 3628800 )</langsyntaxhighlight>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
def 'math factorial' [] {[$in 1] | math max | 1..$in | math product}
 
..10 | each {math factorial}
</syntaxhighlight>
{{out}}
<pre>
╭────┬─────────╮
│ 0 │ 1 │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 6 │
│ 4 │ 24 │
│ 5 │ 120 │
│ 6 │ 720 │
│ 7 │ 5040 │
│ 8 │ 40320 │
│ 9 │ 362880 │
│ 10 │ 3628800 │
╰────┴─────────╯
</pre>
 
=={{header|Nyquist}}==
===Lisp Syntax===
Iterative:
<langsyntaxhighlight Nyquistlang="nyquist">(defun factorial (n)
(do ((x n (* x n)))
((= n 1) x)
(setq n (1- n))))</langsyntaxhighlight>
 
Recursive:
<langsyntaxhighlight Nyquistlang="nyquist">(defun factorial (n)
(if (= n 1)
1
(* n (factorial (1- n)))))</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="modula2">
<lang oberon2>
MODULE Factorial;
IMPORT
Line 5,363 ⟶ 7,358:
END
END Factorial.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,387 ⟶ 7,382:
Recursive 8! =40320
Recursive 9! =362880
</pre>
 
=={{header|Oberon-07}}==
Almost identical to the Oberon-2 sample, with minor output formatting differences.<br/>
Oberon-2 allows single or double quotes to delimit strings whereas Oberon-07 only allows double quotes. Also, the LONGINT type does not exist in Oberon-07 (though some compilers may accept is as a synonym for INTEGER).
<syntaxhighlight lang="modula2">
MODULE Factorial;
IMPORT
Out;
 
VAR
i: INTEGER;
 
PROCEDURE Iterative(n: INTEGER): INTEGER;
VAR
i, r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
FOR i := n TO 2 BY -1 DO
r := r * i
END;
RETURN r
END Iterative;
 
PROCEDURE Recursive(n: INTEGER): INTEGER;
VAR
r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
IF n > 1 THEN
r := n * Recursive(n - 1)
END;
RETURN r
END Recursive;
 
BEGIN
FOR i := 0 TO 9 DO
Out.String("Iterative ");Out.Int(i,0);Out.String("! =");Out.Int(Iterative(i),8);Out.Ln;
END;
Out.Ln;
FOR i := 0 TO 9 DO
Out.String("Recursive ");Out.Int(i,0);Out.String("! =");Out.Int(Recursive(i),8);Out.Ln;
END
END Factorial.
</syntaxhighlight>
{{out}}
<pre>
Iterative 0! = 1
Iterative 1! = 1
Iterative 2! = 2
Iterative 3! = 6
Iterative 4! = 24
Iterative 5! = 120
Iterative 6! = 720
Iterative 7! = 5040
Iterative 8! = 40320
Iterative 9! = 362880
 
Recursive 0! = 1
Recursive 1! = 1
Recursive 2! = 2
Recursive 3! = 6
Recursive 4! = 24
Recursive 5! = 120
Recursive 6! = 720
Recursive 7! = 5040
Recursive 8! = 40320
Recursive 9! = 362880
</pre>
 
=={{header|Objeck}}==
===Iterative===
<langsyntaxhighlight lang="objeck">bundle Default {
class Fact {
function : Main(args : String[]) ~ Nil {
Line 5,397 ⟶ 7,462:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
===Recursive===
<langsyntaxhighlight lang="ocaml">let rec factorial n =
if n <= 0 then 1
else n * factorial (n-1)</langsyntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<langsyntaxhighlight lang="ocaml">let factorial n =
let rec loop i accum =
if i > n then accum
else loop (i + 1) (accum * i)
in loop 1 1</langsyntaxhighlight>
 
===Iterative===
It can be done using explicit state, but this is usually discouraged in a functional language:
<langsyntaxhighlight lang="ocaml">let factorial n =
let result = ref 1 in
for i = 1 to n do
result := !result * i
done;
!result</langsyntaxhighlight>
 
===Bignums===
Line 5,424 ⟶ 7,489:
 
The following code uses the Zarith package to calculate the factorials of larger numbers:
<langsyntaxhighlight lang="ocaml">let rec factorial n =
let rec loop acc = function
| 0 -> acc
Line 5,435 ⟶ 7,500:
Sys.argv.(1) |> int_of_string |> factorial |> Z.print;
print_newline ()
end</langsyntaxhighlight>
 
{{out}}
Line 5,443 ⟶ 7,508:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">% built in factorial
printf("%d\n", factorial(50));
 
Line 5,465 ⟶ 7,530:
endfunction
 
printf("%d\n", iter_fact(50));</langsyntaxhighlight>
 
{{out}}
Line 5,479 ⟶ 7,544:
In fact, all results given by Octave are precise up to their 16th digit, the rest seems to be "random" in all cases. Apparently, this is a consequence of Octave not being capable of arbitrary precision operation.
 
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
 
factorial :: proc(n: int) -> int {
return 1 if n == 0 else n * factorial(n - 1)
}
 
factorial_iterative :: proc(n: int) -> int {
result := 1
for i in 2..=n do result *= i
return result
}
 
main :: proc() {
assert(factorial(4) == 24)
assert(factorial_iterative(4) == 24)
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
Recursive :
<langsyntaxhighlight Oforthlang="oforth">: fact(n) n ifZero: [ 1 ] else: [ n n 1- fact * ] ;</langsyntaxhighlight>
 
Imperative :
<langsyntaxhighlight Oforthlang="oforth">: fact | i | 1 swap loop: i [ i * ] ;</langsyntaxhighlight>
 
{{out}}
Line 5,497 ⟶ 7,579:
=={{header|Order}}==
Simple recursion:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fac \
Line 5,505 ⟶ 7,587:
8mul(8N, 8fac(8dec(8N))))))
 
ORDER_PP(8to_lit(8fac(8))) // 40320</langsyntaxhighlight>
Tail recursion:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fac \
Line 5,517 ⟶ 7,599:
8apply(8F, 8seq_to_tuple(8seq(1, 1, 8F))))))
 
ORDER_PP(8to_lit(8fac(8))) // 40320</langsyntaxhighlight>
 
=={{header|Oz}}==
=== Folding ===
<langsyntaxhighlight lang="oz">fun {Fac1 N}
{FoldL {List.number 1 N 1} Number.'*' 1}
end</langsyntaxhighlight>
=== Tail recursive ===
<langsyntaxhighlight lang="oz">fun {Fac2 N}
fun {Loop N Acc}
if N < 1 then Acc
Line 5,534 ⟶ 7,616:
in
{Loop N 1}
end</langsyntaxhighlight>
=== Iterative ===
<langsyntaxhighlight lang="oz">fun {Fac3 N}
Result = {NewCell 1}
in
Line 5,543 ⟶ 7,625:
end
@Result
end</langsyntaxhighlight>
 
=={{header|Panda}}==
<syntaxhighlight lang="panda">fun fac(n) type integer->integer
product{{1..n}}
 
1..10.fac
</syntaxhighlight>
 
=={{header|PARI/GP}}==
Line 5,549 ⟶ 7,638:
 
===Recursive===
<langsyntaxhighlight lang="parigp">fact(n)=if(n<2,1,n*fact(n-1))</langsyntaxhighlight>
 
===Iterative===
This is an improvement on the naive recursion above, being faster and not limited by stack space.
<langsyntaxhighlight lang="parigp">fact(n)=my(p=1);for(k=2,n,p*=k);p</langsyntaxhighlight>
 
===Binary splitting===
PARI's <code>factorback</code> automatically uses binary splitting, preventing subproducts from growing overly large. This function is dramatically faster than the above.
<langsyntaxhighlight lang="parigp">fact(n)=factorback([2..n])</langsyntaxhighlight>
 
===Recursive 1===
Even faster
<langsyntaxhighlight lang="parigp">f( a, b )={
my(c);
if( b == a, return(a));
Line 5,571 ⟶ 7,660:
}
 
fact(n) = f(1, n)</langsyntaxhighlight>
 
===Built-in===
Uses binary splitting. According to the source, this was found to be faster than prime decomposition methods. This is, of course, faster than the above.
<langsyntaxhighlight lang="parigp">fact(n)=n!</langsyntaxhighlight>
 
===Gamma===
Note also the presence of <code>factorial</code> and <code>lngamma</code>.
<langsyntaxhighlight lang="parigp">fact(n)=round(gamma(n+1))</langsyntaxhighlight>
 
===Moessner's algorithm===
Line 5,585 ⟶ 7,674:
:Alfred Moessner, "Eine Bemerkung über die Potenzen der natürlichen Zahlen." ''S.-B. Math.-Nat. Kl. Bayer. Akad. Wiss.'' '''29''':3 (1952).
This is very slow but should be able to compute factorials until it runs out of memory (usage is about <math>n^2\log n</math> bits to compute n!); a machine with 1 GB of RAM and unlimited time could, in theory, find 100,000-digit factorials.
<langsyntaxhighlight lang="parigp">fact(n)={
my(v=vector(n+1,i,i==1));
for(i=2,n+1,
Line 5,593 ⟶ 7,682:
);
v[n+1]
};</langsyntaxhighlight>
 
=={{header|Panda}}==
<lang panda>fun fac(n) type integer->integer
product{{1..n}}
 
1..10.fac
</lang>
 
=={{header|Pascal}}==
=== Iterative ===
<langsyntaxhighlight lang="pascal">function factorial(n: integer): integer;
var
i, result: integer;
Line 5,612 ⟶ 7,694:
result := result * i;
factorial := result
end;</langsyntaxhighlight>
=== Iterative FreePascal ===
<syntaxhighlight lang="pascal">
{$mode objFPC}{R+}
FUNCTION Factorial ( n : qword ) : qword;
 
(*)
Update for version 3.2.0
Factorial works until 20! , which is good enough for me for now
replace qword with dword and rax,rcx with eax, ecx for 32-bit
for Factorial until 12!
(*)
 
VAR
F: qword;
BEGIN
 
asm
mov $1, %rax
mov n, %rcx
.Lloop1:
imul %rcx, %rax
loopnz .Lloop1
mov %rax, F
 
end;
 
Result := F ;
END;</syntaxhighlight>
JPD 2021/03/24
 
=== using FreePascal with GMP lib===
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM EXBigFac ;
 
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
 
(*)
 
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI *
Can run independently from DELPHI / Lazarus
 
For debian Linux: apt -y install fpc
It contains a text IDE called fp
 
https://www.freepascal.org/advantage.var
 
(*)
 
 
USES
 
gmp;
 
FUNCTION WriteBigNum ( c: pchar ) : ansistring ;
 
CONST
 
CrLf = #13 + #10 ;
 
VAR
i: longint;
len: longint;
preview: integer;
ret: ansistring = '';
threshold: integer;
 
BEGIN
 
len := length ( c ) ;
WriteLn ( 'Digits: ', len ) ;
threshold := 12 ;
preview := len div threshold ;
IF ( len < 91 ) THEN
BEGIN
FOR i := 0 TO len DO
ret:= ret + c [ i ] ;
END
ELSE
BEGIN
FOR i := 0 TO preview DO
ret:= ret + c [ i ] ;
ret:= ret + '...' ;
FOR i := len - preview -1 TO len DO
ret:= ret + c [ i ] ;
END;
ret:= ret + CrLf ;
WriteBigNum := ret;
END;
 
FUNCTION BigFactorial ( n : qword ) : ansistring ;
 
(*)
See https://gmplib.org/#DOC
(*)
 
VAR
S: mpz_t;
c: pchar;
 
BEGIN
 
mpz_init_set_ui ( S, 1 ) ;
mpz_fac_ui ( S, n ) ;
c := mpz_get_str ( NIL, 10, S ) ;
BigFactorial := WriteBigNum ( c ) ;
END;
 
BEGIN
 
WriteLn ( BigFactorial ( 99 ) ) ;
 
END.
 
Output:
Digits: 156
93326215443944...00000000000000
</syntaxhighlight>JPD 2021/05/15
 
=== Recursive ===
<langsyntaxhighlight lang="pascal">function factorial(n: integer): integer;
begin
if n = 0
Line 5,621 ⟶ 7,836:
else
factorial := n*factorial(n-1)
end;</langsyntaxhighlight>
 
=={{header|Pebble}}==
<syntaxhighlight lang="pebble">;Factorial example program for x86 DOS
;Compiles to 207 bytes com executable
 
program examples\fctrl
 
data
 
int f[1]
int n[0]
 
begin
 
echo "Factorial"
echo "Enter an integer: "
 
input [n]
 
label loop
 
[f] = [f] * [n]
 
-1 [n]
 
if [n] > 0 then loop
 
echo [f]
pause
kill
 
end</syntaxhighlight>
 
=={{header|Peloton}}==
Peloton has an opcode for factorial so there's not much point coding one.
<syntaxhighlight lang ="sgml"><@ SAYFCTLIT>5</@></langsyntaxhighlight>
However, just to prove that it can be done, here's one possible implementation:
<langsyntaxhighlight lang="sgml"><@ DEFUDOLITLIT>FAT|__Transformer|<@ LETSCPLIT>result|1</@><@ ITEFORPARLIT>1|<@ ACTMULSCPPOSFOR>result|...</@></@><@ LETRESSCP>...|result</@></@>
<@ SAYFATLIT>123</@></langsyntaxhighlight>
 
=={{header|Perl}}==
=== Iterative ===
<langsyntaxhighlight lang="perl">sub factorial
{
my $n = shift;
Line 5,648 ⟶ 7,895:
$r *= $_ for 1..shift;
$r;
}</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="perl">sub factorial
{
my $n = shift;
($n == 0)? 1 : $n*factorial($n-1);
}</langsyntaxhighlight>
=== Functional ===
<langsyntaxhighlight lang="perl">use List::Util qw(reduce);
sub factorial
{
my $n = shift;
reduce { $a * $b } 1, 1 .. $n
}</langsyntaxhighlight>
=== Modules ===
Each of these will print 35660, the number of digits in 10,000!.
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/factorial/;
# factorial returns a UV (native unsigned int) or Math::BigInt depending on size
say length( factorial(10000) );</langsyntaxhighlight>
<langsyntaxhighlight lang="perl">use bigint;
say length( 10000->bfac );</langsyntaxhighlight>
<langsyntaxhighlight lang="perl">use Math::GMP;
say length( Math::GMP->new(10000)->bfac );</langsyntaxhighlight>
<langsyntaxhighlight lang="perl">use Math::Pari qw/ifact/;
say length( ifact(10000) );</langsyntaxhighlight>
 
=={{header|Perl 6Peylang}}==
<syntaxhighlight lang="peylang">
=== via User-defined Postfix Operator ===
-- calculate factorial
<tt>[*]</tt> is a reduction operator that multiplies all the following values together. Note that we don't need to start at 1, since the degenerate case of <tt>[*]()</tt> correctly returns 1, and multiplying by 1 to start off with is silly in any case.
{{works with|Rakudo|2015.12}}
<lang perl6>sub postfix:<!> (Int $n) { [*] 2..$n }
say 5!;</lang>
{{out}}<pre>120</pre>
 
chiz a = 5;
=== via Memoized Constant Sequence ===
chiz n = 1;
This approach is much more efficient for repeated use, since it automatically caches. <tt>[\*]</tt> is the so-called triangular version of [*]. It returns the intermediate results as a list. Note that Perl 6 allows you to define constants lazily, which is rather helpful when your constant is of infinite size...
 
{{works with|Rakudo|2015.12}}
ta a >= 2
<lang perl6>constant fact = 1, |[\*] 1..*;
{
say fact[5]</lang>
n *= a;
{{out}}<pre>120</pre>
a -= 1;
}
 
chaap n;
</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
standard iterative factorial builtin, reproduced below. returns inf for 171 and above, and is not accurate above 22 on 32-bit, or 25 on 64-bit.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>global function factorial(integer n)
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">factorial<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">n<span style="color: #0000FF;">)</span>
atom res = 1
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
while n>1 do
<span style="color: #008080;">while</span> <span style="color: #000000;">n<span style="color: #0000FF;">><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
res *= n
<span style="color: #000000;">res</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">n</span>
n -= 1
<span style="color: #000000;">n</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<!--</syntaxhighlight>-->
The compiler knows where to find that for you, so a runnable program is just
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">factorial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
40320
</pre>
 
=== gmp ===
{{libheader|Phix/mpfr}}
For seriously big numbers, with perfect accuracy, use the mpz_fac_ui() routine. For a bit of fun, we'll see just how far we can push it, in ten seconds or less.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include mpfr.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
mpz f = mpz_init()
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
integer n = 2
<span style="color: #004080;">mpz</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
bool still_running = true,
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
still_printing = true
<span style="color: #004080;">bool</span> <span style="color: #000000;">still_running</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span><span style="color: #0000FF;">,</span>
while still_running do
<span style="color: #000000;">still_printing</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
atom t0 = time()
<span style="color: #008080;">constant</span> <span style="color: #000000;">ten_s</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0.2</span><span style="color: #0000FF;">:</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (10s on desktop/Phix, 0.2s under p2js)</span>
mpz_fac_ui(f, n)
<span style="color: #008080;">while</span> <span style="color: #000000;">still_running</span> <span style="color: #008080;">do</span>
still_running = (time()-t0)<10 -- (stop once over 10s)
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
string ct = elapsed(time()-t0), res, what, pt
<span style="color: #7060A8;">mpz_fac_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
t0 = time()
<span style="color: #000000;">still_running</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">ten_s</span> <span style="color: #000080;font-style:italic;">-- (stop once over 10s)</span>
if still_printing then
<span style="color: #004080;">string</span> <span style="color: #000000;">ct</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pt</span>
res = shorten(mpz_get_str(f))
<span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
what = "printed"
<span style="color: #008080;">if</span> <span style="color: #000000;">still_printing</span> <span style="color: #008080;">then</span>
still_printing = (time()-t0)<10 -- (stop once over 10s)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">))</span>
else
<span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"printed"</span>
res = sprintf("%,d digits",mpz_sizeinbase(f,10))
<span style="color: #000000;">still_printing</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">ten_s</span> <span style="color: #000080;font-style:italic;">-- (stop once over 10s)</span>
what = "size in base"
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%,d digits"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_sizeinbase</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
pt = elapsed(time()-t0)
<span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"size in base"</span>
printf(1,"factorial(%d):%s, calculated in %s, %s in %s\n",
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
{n,res,ct,what,pt})
<span style="color: #000000;">pt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
n *= 2
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"factorial(%d):%s, calculated in %s, %s in %s\n"</span><span style="color: #0000FF;">,</span>
end while</lang>
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ct</span><span style="color: #0000FF;">,</span><span style="color: #000000;">what</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 5,756 ⟶ 8,020:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">/# recursive #/
def factorial
dup 1 > if
Line 5,772 ⟶ 8,036:
0 22 2 tolist for
"Factorial(" print dup print ") = " print factorial2 print nl
endfor</langsyntaxhighlight>
 
=={{header|PHP}}==
=== Iterative ===
<langsyntaxhighlight lang="php"><?php
function factorial($n) {
if ($n < 0) {
Line 5,789 ⟶ 8,053:
return $factorial;
}
?></langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="php"><?php
function factorial($n) {
if ($n < 0) {
Line 5,805 ⟶ 8,069:
}
}
?></langsyntaxhighlight>
=== One-Liner ===
<langsyntaxhighlight lang="php"><?php
function factorial($n) { return $n == 0 ? 1 : array_product(range(1, $n)); }
?></langsyntaxhighlight>
 
=== Library ===
Requires the GMP library to be compiled in:
<syntaxhighlight lang ="php">gmp_fact($n)</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">fact(N) = prod(1..N)</syntaxhighlight>
 
Note: Picat has <code>factorial/1</code> as a built-in function.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de fact (N)
(if (=0 N)
1
(* N (fact (dec N))) ) )</langsyntaxhighlight>
 
or:
<langsyntaxhighlight PicoLisplang="picolisp">(de fact (N)
(apply * (range 1 N) ) )</langsyntaxhighlight>
which only works for 1 and bigger.
 
Line 5,832 ⟶ 8,101:
 
This is the text code. It is a bit difficult to write as there are some loops and loops doesn't really show well when I write it down as there is no way to explicitly write a loop in the language. I have tried to comment as best to show how it works
<langsyntaxhighlight lang="pseudocode">push 1
not
in(number)
Line 5,868 ⟶ 8,137:
pop // continues from pointer 2
out(number)
exit</langsyntaxhighlight>
 
=={{header|Plain English}}==
Due to the compiler being implemented in 32-bit, this implementation can calculate only up to 12!.
<syntaxhighlight lang="plainenglish">A factorial is a number.
 
To run:
Start up.
Demonstrate input.
Write "Bye-bye!" to the console.
Wait for 1 second.
Shut down.
To demonstrate input:
Write "Enter a number: " to the console without advancing.
Read a string from the console.
If the string is empty, exit.
Convert the string to a number.
If the number is negative, repeat.
Compute a factorial of the number.
Write "Factorial of the number: " then the factorial then the return byte to the console.
Repeat.
 
To decide if a string is empty:
If the string's length is 0, say yes.
Say no.
 
To compute a factorial of a number:
If the number is 0, put 1 into the factorial; exit.
Compute another factorial of the number minus 1. \ recursion
Put the other factorial times the number into the factorial.</syntaxhighlight>
 
=={{header|PL/0}}==
The program waits for ''n''. Then it displays ''n''!.
<syntaxhighlight lang="pascal">
var n, f;
begin
? n;
f := 1;
while n <> 0 do
begin
f := f * n;
n := n - 1
end;
! f
end.
</syntaxhighlight>
2 runs.
{{in}}
<pre>5</pre>
{{out}}
<pre> 120</pre>
{{in}}
<pre>7</pre>
{{out}}
<pre> 5040</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">factorial: procedure (N) returns (fixed decimal (30));
declare N fixed binary nonassignable;
declare i fixed decimal (10);
Line 5,882 ⟶ 8,206:
end;
return (F);
end factorial;</langsyntaxhighlight>
 
=={{header|PL/SQL}}==
<syntaxhighlight lang="plsql">
Declare
/*====================================================================================================
-- For : https://rosettacode.org/
-- --
-- Task : Factorial
-- Method : iterative
-- Language: PL/SQL
--
-- 2020-12-30 by alvalongo
====================================================================================================*/
--
function fnuFactorial(inuValue integer)
return number
is
nuFactorial number;
Begin
if inuValue is not null then
nuFactorial:=1;
--
if inuValue>=1 then
--
For nuI in 1..inuValue loop
nuFactorial:=nuFactorial*nuI;
end loop;
--
End if;
--
End if;
--
return(nuFactorial);
End fnuFactorial;
BEGIN
For nuJ in 0..100 loop
Dbms_Output.Put_Line('Factorial('||nuJ||')='||fnuFactorial(nuJ));
End loop;
END;
</syntaxhighlight>
{{out}}
<pre>
Text
PL/SQL block, executed in 115 ms
Factorial(0)=1
Factorial(1)=1
Factorial(2)=2
Factorial(3)=6
Factorial(4)=24
Factorial(5)=120
Factorial(6)=720
Factorial(7)=5040
Factorial(8)=40320
Factorial(9)=362880
Factorial(10)=3628800
Factorial(11)=39916800
Factorial(12)=479001600
Factorial(13)=6227020800
Factorial(14)=87178291200
Factorial(15)=1307674368000
Factorial(16)=20922789888000
Factorial(17)=355687428096000
Factorial(18)=6402373705728000
Factorial(19)=121645100408832000
Factorial(20)=2432902008176640000
Factorial(21)=51090942171709440000
Factorial(22)=1124000727777607680000
Factorial(23)=25852016738884976640000
Factorial(24)=620448401733239439360000
Factorial(25)=15511210043330985984000000
Factorial(26)=403291461126605635584000000
Factorial(27)=10888869450418352160768000000
Factorial(28)=304888344611713860501504000000
Factorial(29)=8841761993739701954543616000000
Factorial(30)=265252859812191058636308480000000
Factorial(31)=8222838654177922817725562880000000
Factorial(32)=263130836933693530167218012160000000
Factorial(33)=8683317618811886495518194401280000000
Factorial(34)=295232799039604140847618609643520000000
Factorial(35)=10333147966386144929666651337523200000000
Factorial(36)=371993326789901217467999448150835200000000
Factorial(37)=13763753091226345046315979581580902400000000
Factorial(38)=523022617466601111760007224100074291200000000
Factorial(39)=20397882081197443358640281739902897356800000000
Factorial(40)=815915283247897734345611269596115894272000000000
Factorial(41)=33452526613163807108170062053440751665150000000000
Factorial(42)=1405006117752879898543142606244511569936000000000000
Factorial(43)=60415263063373835637355132068513997507200000000000000
Factorial(44)=2658271574788448768043625811014615890320000000000000000
Factorial(45)=119622220865480194561963161495657715064000000000000000000
Factorial(46)=5502622159812088949850305428800254892944000000000000000000
Factorial(47)=258623241511168180642964355153611979968400000000000000000000
Factorial(48)=12413915592536072670862289047373375038480000000000000000000000
Factorial(49)=608281864034267560872252163321295376886000000000000000000000000
Factorial(50)=30414093201713378043612608166064768844300000000000000000000000000
Factorial(51)=1551118753287382280224243016469303211060000000000000000000000000000
Factorial(52)=80658175170943878571660636856403766975120000000000000000000000000000
Factorial(53)=4274883284060025564298013753389399649681000000000000000000000000000000
Factorial(54)=230843697339241380472092742683027581082800000000000000000000000000000000
Factorial(55)=12696403353658275925965100847566516959550000000000000000000000000000000000
Factorial(56)=710998587804863451854045647463724949735000000000000000000000000000000000000
Factorial(57)=40526919504877216755680601905432322134900000000000000000000000000000000000000
Factorial(58)=2350561331282878571829474910515074683820000000000000000000000000000000000000000
Factorial(59)=138683118545689835737939019720389406345000000000000000000000000000000000000000000
Factorial(60)=8320987112741390144276341183223364380700000000000000000000000000000000000000000000
Factorial(61)=507580213877224798800856812176625227222700000000000000000000000000000000000000000000
Factorial(62)=31469973260387937525653122354950764087810000000000000000000000000000000000000000000000
Factorial(63)=1982608315404440064116146708361898137532000000000000000000000000000000000000000000000000
Factorial(64)=126886932185884164103433389335161480802000000000000000000000000000000000000000000000000000
Factorial(65)=8247650592082470666723170306785496252130000000000000000000000000000000000000000000000000000
Factorial(66)=544344939077443064003729240247842752641000000000000000000000000000000000000000000000000000000
Factorial(67)=36471110918188685288249859096605464426900000000000000000000000000000000000000000000000000000000
Factorial(68)=2480035542436830599600990418569171581030000000000000000000000000000000000000000000000000000000000
Factorial(69)=171122452428141311372468338881272839091000000000000000000000000000000000000000000000000000000000000
Factorial(70)=1,197857166996989179607278372168909873640000000000000000000000000000000000000000000000000000000E+100
Factorial(71)=8,504785885678623175211676442399260102844000000000000000000000000000000000000000000000000000000E+101
Factorial(72)=6,123445837688608686152407038527467274048000000000000000000000000000000000000000000000000000000E+103
Factorial(73)=4,470115461512684340891257138125051110055000000000000000000000000000000000000000000000000000000E+105
Factorial(74)=3,307885441519386412259530282212537821441000000000000000000000000000000000000000000000000000000E+107
Factorial(75)=2,480914081139539809194647711659403366081000000000000000000000000000000000000000000000000000000E+109
Factorial(76)=1,885494701666050254987932260861146558222000000000000000000000000000000000000000000000000000000E+111
Factorial(77)=1,451830920282858696340707840863082849831000000000000000000000000000000000000000000000000000000E+113
Factorial(78)=1,132428117820629783145752115873204622868000000000000000000000000000000000000000000000000000000E+115
Factorial(79)=8,946182130782975286851441715398316520660000000000000000000000000000000000000000000000000000000E+116
Factorial(80)=7,156945704626380229481153372318653216530000000000000000000000000000000000000000000000000000000E+118
Factorial(81)=5,797126020747367985879734231578109105390000000000000000000000000000000000000000000000000000000E+120
Factorial(82)=4,753643337012841748421382069894049466420000000000000000000000000000000000000000000000000000000E+122
Factorial(83)=3,945523969720658651189747118012061057130000000000000000000000000000000000000000000000000000000E+124
Factorial(84)=~
Factorial(85)=~
Factorial(86)=~
Factorial(87)=~
Factorial(88)=~
Factorial(89)=~
Factorial(90)=~
Factorial(91)=~
Factorial(92)=~
Factorial(93)=~
Factorial(94)=~
Factorial(95)=~
Factorial(96)=~
Factorial(97)=~
Factorial(98)=~
Factorial(99)=~
Factorial(100)=~
Total execution time 176 ms
</pre>
 
=={{header|PostScript}}==
===Recursive===
<langsyntaxhighlight lang="postscript">/fact {
dup 0 eq % check for the argument being 0
{
Line 5,897 ⟶ 8,368:
mul % multiply the result with n
} ifelse
} def</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="postscript">/fact {
1 % initial value for the product
1 1 % for's start value and increment
4 -1 roll % bring the argument to the top as for's end value
{ mul } for
} def</langsyntaxhighlight>
===Combinator===
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">/myfact {{dup 0 eq} {pop 1} {dup pred} {mul} linrec}.</langsyntaxhighlight>
 
=={{header|PowerBASIC}}==
<lang powerbasic>function fact1#(n%)
local i%,r#
r#=1
for i%=1 to n%
r#=r#*i%
next
fact1#=r#
end function
 
function fact2#(n%)
if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n%
end function
 
for i%=1 to 20
print i%,fact1#(i%),fact2#(i%)
next</lang>
 
=={{header|PowerShell}}==
===Recursive===
<langsyntaxhighlight lang="powershell">function Get-Factorial ($x) {
if ($x -eq 0) {
return 1
}
return $x * (Get-Factorial ($x - 1))
}</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="powershell">function Get-Factorial ($x) {
if ($x -eq 0) {
return 1
Line 5,944 ⟶ 8,397:
return $product
}
}</langsyntaxhighlight>
===Evaluative===
{{works with|PowerShell|2}}
This one first builds a string, containing <code>1*2*3...</code> and then lets PowerShell evaluate it. A bit of mis-use but works.
<langsyntaxhighlight lang="powershell">function Get-Factorial ($x) {
if ($x -eq 0) {
return 1
}
return (Invoke-Expression (1..$x -join '*'))
}</langsyntaxhighlight>
 
=={{header|Processing}}==
===Recursive===
<lang processing>
<syntaxhighlight lang="processing">
int fact(int n){
if(n <= 1){
Line 5,964 ⟶ 8,418:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
<pre>
returns the appropriate value as an int
</pre>
===Iterative===
<syntaxhighlight lang="processing">
long fi(int n) {
if (n < 0){
return -1;
}
if (n == 0){
return 1;
} else {
long r = 1;
for (long i = 1; i <= n; i++){
r = r * i;
}
return r;
}
}
</syntaxhighlight>
{{out}}
<pre>
for n < 0 the function returns -1 as an error code.
for n >= 0 the appropriate value is returned as a long.
</pre>
 
Line 5,974 ⟶ 8,452:
{{works with|SWI Prolog}}
===Recursive===
<langsyntaxhighlight lang="prolog">fact(X, 1) :- X<2.
fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*X.</langsyntaxhighlight>
===Tail recursive===
<langsyntaxhighlight lang="prolog">fact(N, NF) :-
fact(1, N, 1, NF).
 
Line 5,984 ⟶ 8,462:
X1 is X + 1,
FX1 is FX * X1,
fact(X1, N, FX1, F).</langsyntaxhighlight>
 
===Fold===
We can simulate foldl.
<langsyntaxhighlight lang="prolog">% foldl(Pred, Init, List, R).
%
foldl(_Pred, Val, [], Val).
Line 6,000 ⟶ 8,478:
fact(X, F) :-
numlist(2, X, L),
foldl(p, 1, L, F).</langsyntaxhighlight>
===Fold with anonymous function===
Using the module lambda written by Ulrich Neumerkel found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl, we can use anonymous functions and write :
<langsyntaxhighlight lang="prolog">:- use_module(lambda).
 
% foldl(Pred, Init, List, R).
Line 6,014 ⟶ 8,492:
fact(N, F) :-
numlist(2, N, L),
foldl(\X^Y^Z^(Z is X * Y), 1, L, F).</langsyntaxhighlight>
===Continuation passing style===
Works with SWI-Prolog and module lambda written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl.
<langsyntaxhighlight lang="prolog">:- use_module(lambda).
 
fact(N, FN) :-
Line 6,030 ⟶ 8,508:
cont_fact(N1, FT, P),
call(Pred, FT, F)
).</langsyntaxhighlight>
 
=={{header|Pure}}==
===Recursive===
<langsyntaxhighlight lang="pure">fact n = n*fact (n-1) if n>0;
= 1 otherwise;
let facts = map fact (1..10); facts;</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="pure">fact n = loop 1 n with
loop p n = if n>0 then loop (p*n) (n-1) else p;
end;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
===Iterative===
<lang PureBasic>Procedure factorial(n)
Protected i, f = 1
For i = 2 To n
f = f * i
Next
ProcedureReturn f
EndProcedure</lang>
===Recursive===
<lang PureBasic>Procedure Factorial(n)
If n < 2
ProcedureReturn 1
Else
ProcedureReturn n * Factorial(n - 1)
EndIf
EndProcedure</lang>
 
=={{header|Python}}==
===Library===
{{works with|Python|2.6+, 3.x}}
<langsyntaxhighlight lang="python">import math
math.factorial(n)</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="python">def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result</langsyntaxhighlight>
===Functional===
<langsyntaxhighlight lang="python">from operator import mul
from functools import reduce
 
def factorial(n):
return reduce(mul, range(1,n+1), 1)</langsyntaxhighlight>
 
or
<langsyntaxhighlight lang="python">from itertools import (accumulate, chain)
from operator import mul
 
Line 6,086 ⟶ 8,546:
return list(
accumulate(chain([1], range(1, 1 + n)), mul)
)[-1]</langsyntaxhighlight>
 
or including the sequence that got us there:
<langsyntaxhighlight lang="python">from itertools import (accumulate, chain)
from operator import mul
 
Line 6,101 ⟶ 8,561:
print(factorials(5))
 
# -> [1, 1, 2, 6, 24, 120]</langsyntaxhighlight>
 
or
<langsyntaxhighlight lang="python">from numpy import prod
 
def factorial(n):
return prod(range(1, n + 1), dtype=int)</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="python">def factorial(n):
z=1
if n>1:
z=n*factorial(n-1)
return z</langsyntaxhighlight>
 
{{out}}
Line 6,129 ⟶ 8,589:
 
or
<langsyntaxhighlight lang="python">def factorial(n):
return n * factorial(n - 1) if n else 1</langsyntaxhighlight>
 
===Numerical Approximation===
Line 6,136 ⟶ 8,596:
 
The gamma function Γ(x) extends the domain of the factorial function, while maintaining the relationship that factorial(x) = Γ(x+1).
<langsyntaxhighlight lang="python">from cmath import *
 
# Coefficients used by the GNU Scientific Library
Line 6,162 ⟶ 8,622:
print "factorial(-0.5)**2=",factorial(-0.5)**2
for i in range(10):
print "factorial(%d)=%s"%(i,factorial(i))</langsyntaxhighlight>
{{out}}
<pre>
Line 6,181 ⟶ 8,641:
===Iterative===
====Point-free====
<syntaxhighlight lang Q="q">f:(*/)1+til@</langsyntaxhighlight>
or
<syntaxhighlight lang Q="q">f:(*)over 1+til@</langsyntaxhighlight>
or
<syntaxhighlight lang Q="q">f:prd 1+til@</langsyntaxhighlight>
====As a function====
<langsyntaxhighlight Qlang="q">f:{(*/)1+til x}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight Qlang="q">f:{$[x=1;1;x*.z.s x-1]}</langsyntaxhighlight>
 
=={{header|QB64Quackery}}==
===Iterative===
<lang QB64>
REDIM fac#(0)
Factorial fac#(), 655, 10, power#
PRINT power#
SUB Factorial (fac#(), n&, numdigits%, power#)
power# = 0
fac#(0) = 1
remain# = 0
stx& = 0
slog# = 0
NumDiv# = 10 ^ numdigits%
FOR fac# = 1 TO n&
slog# = slog# + LOG(fac#) / LOG(10)
FOR x& = 0 TO stx&
fac#(x&) = fac#(x&) * fac# + remain#
tx# = fac#(x&) MOD NumDiv#
remain# = (fac#(x&) - tx#) / NumDiv#
fac#(x&) = tx#
NEXT
IF remain# > 0 THEN
stx& = UBOUND(fac#) + 1
REDIM _PRESERVE fac#(stx&)
fac#(stx&) = remain#
remain# = 0
END IF
NEXT
 
<syntaxhighlight lang="quackery"> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n! )</syntaxhighlight>
scanz& = LBOUND(fac#)
DO
IF scanz& < UBOUND(fac#) THEN
IF fac#(scanz&) THEN
EXIT DO
ELSE
scanz& = scanz& + 1
END IF
ELSE
EXIT DO
END IF
LOOP
 
===Overly Complicated and Inefficient===
FOR x& = UBOUND(fac#) TO scanz& STEP -1
 
m$ = LTRIM$(RTRIM$(STR$(fac#(x&))))
Words named in the form [Annnnnn] refer to entries in the
IF x& < UBOUND(fac#) THEN
The On-Line Encyclopedia of Integer Sequences® [https://oeis.org].
WHILE LEN(m$) < numdigits%
 
m$ = "0" + m$
<syntaxhighlight lang="quackery"> [ 1 & ] is odd ( n --> b )
WEND
 
END IF
[ odd not ] is even ( n --> b )
PRINT m$; " ";
 
power# = power# + LEN(m$)
[ 1 >> ] is 2/ ( n --> n )
NEXT
 
power# = power# + (scanz& * numdigits%) - 1
[ [] swap
PRINT slog#
witheach
END SUB
[ i^ swap - join ] ] is [i^-] ( [ --> [ )
</lang>
 
[ 1 split
witheach
[ over -1 peek
* join ] ] is [prod] ( [ --> [ )
 
[ 1 - ' [ 0 ]
swap times
[ dup i^ 1+
dup dip
[ 2/ peek ]
odd +
join ] ] is [A000120] ( n --> [ )
 
 
[ [A000120] [i^-] ] is [A011371] ( n --> [ )
 
[ ' [ 0 ] swap
1 - times
[ i^ 1+ dup even if
[ dip dup 2/ peek ]
join ]
behead drop ] is [A000265] ( n --> [ )
 
[ ' [ 1 ] swap dup
[A000265] [prod]
swap [A011371]
swap witheach
[ over i^ 1+ peek
<< rot swap join
swap ] drop ] is [A000142] ( n --> [ )
 
[ 1+ [A000142] -1 peek ] is !
</syntaxhighlight>
 
=={{header|R}}==
=== Recursive ===
<langsyntaxhighlight Rlang="r">fact <- function(n) {
if (n <= 1) 1
else n * Recall(n - 1)
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight Rlang="r">factIter <- function(n) {
f = 1
if (n > 1) {
Line 6,262 ⟶ 8,719:
}
f
}</langsyntaxhighlight>
 
===Numerical Approximation===
R has a native gamma function and a wrapper for that function that can produce factorials. E.g.
<langsyntaxhighlight Rlang="r">print(factorial(50)) # 3.041409e+64</langsyntaxhighlight>
 
=={{header|Racket}}==
=== Recursive ===
The standard recursive style:
<langsyntaxhighlight Racketlang="racket">(define (factorial n)
(if (= 0 n)
1
(* n (factorial (- n 1)))))</langsyntaxhighlight>
 
However, it is inefficient. It's more efficient to use an accumulator.
 
<langsyntaxhighlight Racketlang="racket">(define (factorial n)
(define (fact n acc)
(if (= 0 n)
acc
(fact (- n 1) (* n acc))))
(fact n 1))</langsyntaxhighlight>
 
=== Fold ===
We can also define factorial as for/fold (product startvalue) (range) (operation))
 
<langsyntaxhighlight Racketlang="racket">(define (factorial n)
(for/fold ([pro 1]) ([i (in-range 1 (+ n 1))]) (* pro i)))</langsyntaxhighlight>
 
Or quite simpler by an for/product
 
<langsyntaxhighlight Racketlang="racket">(define (factorial n)
(for/product ([i (in-range 1 (+ n 1))]) i))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
=== via User-defined Postfix Operator ===
<tt>[*]</tt> is a reduction operator that multiplies all the following values together. Note that we don't need to start at 1, since the degenerate case of <tt>[*]()</tt> correctly returns 1, and multiplying by 1 to start off with is silly in any case.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>sub postfix:<!> (Int $n) { [*] 2..$n }
say 5!;</syntaxhighlight>
{{out}}<pre>120</pre>
 
=== via Memoized Constant Sequence ===
This approach is much more efficient for repeated use, since it automatically caches. <tt>[\*]</tt> is the so-called triangular version of [*]. It returns the intermediate results as a list. Note that Raku allows you to define constants lazily, which is rather helpful when your constant is of infinite size...
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>constant fact = 1, |[\*] 1..*;
say fact[5]</syntaxhighlight>
{{out}}<pre>120</pre>
 
=={{header|Rapira}}==
=== Iterative ===
<langsyntaxhighlight lang="rapira">Фун Факт(n)
f := 1
для i от 1 до n
Line 6,304 ⟶ 8,777:
кц
Возврат f
Кон Фун</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang="rapira">Фун Факт(n)
Если n = 1
Возврат 1
Line 6,319 ⟶ 8,792:
печать 'n! = '
печать Факт(n)
Кон проц </langsyntaxhighlight>
 
=== Recursive (English) ===
<syntaxhighlight lang="rapira">fun factorial(number)
if number = 0 then
return 1
fi
 
return number * factorial(number - 1)
end</syntaxhighlight>
 
=={{header|Rascal}}==
===Iterative===
The standard implementation:
<langsyntaxhighlight lang="rascal">public int factorial_iter(int n){
result = 1;
for(i <- [1..n])
result *= i;
return result;
}</langsyntaxhighlight>
However, Rascal supports an even neater solution.
By using a [http://tutor.rascal-mpl.org/Courses/Rascal/Libraries/lang/xml/DOM/xmlPretty/xmlPretty.html#/Courses/Rascal/Expressions/Reducer/Reducer.html reducer] we can write this code on one short line:
<langsyntaxhighlight lang="rascal">public int factorial_iter2(int n) = (1 | it*e | int e <- [1..n]);</langsyntaxhighlight>
{{out}}
<pre>rascal>factorial_iter(10)
Line 6,341 ⟶ 8,823:
 
===Recursive===
<langsyntaxhighlight lang="rascal">public int factorial_rec(int n){
if(n>1) return n*factorial_rec(n-1);
else return 1;
}</langsyntaxhighlight>
{{out}}
<pre>rascal>factorial_rec(10)
int: 3628800</pre>
 
=={{header|RASEL}}==
<syntaxhighlight lang="text">1&$:?v:1-3\$/1\
>$11\/.@</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Factorial"
URL: http://rosettacode.org/wiki/Factorial_function
Line 6,404 ⟶ 8,890:
; Test them on numbers zero to ten.
for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]]</langsyntaxhighlight>
{{out}}
<pre>0 : 1 1 1
Line 6,418 ⟶ 8,904:
10 : 3628800 3628800 3628800</pre>
* See also [[wp:Memoization|more on memoization...]]
 
=={{header|Red}}==
Iterative (variants):
<syntaxhighlight lang="red">fac: function [n][r: 1 repeat i n [r: r * i] r]
fac: function [n][repeat i also n n: 1 [n: n * i] n]</syntaxhighlight>
Recursive (variants):
<syntaxhighlight lang="red">fac: func [n][either n > 1 [n * fac n - 1][1]]
fac: func [n][any [if n = 0 [1] n * fac n - 1]]
fac: func [n][do pick [[n * fac n - 1] 1] n > 1]</syntaxhighlight>
Memoized:
<syntaxhighlight lang="red">fac: function [n][m: #(0 1) any [m/:n m/:n: n * fac n - 1]]</syntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Facts 0 10>;
}
 
Facts {
s.N s.Max, <Compare s.N s.Max>: '+' = ;
s.N s.Max = <Prout <Symb s.N>'! = ' <Fact s.N>>
<Facts <+ s.N 1> s.Max>;
};
 
Fact {
0 = 1;
s.N = <* s.N <Fact <- s.N 1>>>;
};</syntaxhighlight>
{{out}}
<pre>0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800</pre>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
function factorial (n)
set result = 1
if n > 1
set k = 2
while k <= n
set result = result * k
set k = k + 1
end while
end if
end function
</syntaxhighlight>
 
=={{header|Retro}}==
A recursive implementation from the benchmarking code.
<langsyntaxhighlight Retrolang="retro">: <factorial> dup 1 = if; dup 1- <factorial> * ;
: factorial dup 0 = [ 1+ ] [ <factorial> ] if ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 6,429 ⟶ 8,968:
<br><br> <big> 25,000'''!''' </big> &nbsp; is exactly &nbsp; <big> 99,094 </big> &nbsp; decimal digits.
<br><br>Most REXX interpreters can handle eight million decimal digits.
<langsyntaxhighlight lang="rexx">/*REXX program pgm computes & shows the factorial of a non-negativenon─negative integer. , and also its length*/
numeric digits 100000 /*100k digits: handles N up to 25k.*/
parse arg n /*obtain optional argument from the CL.*/
Line 6,437 ⟶ 8,976:
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 1 /*define the factorial product (so far)*/
do j=2 to n; !=!*j /*compute the factorial the hard way. */
end /*j*/ /* [↑] where da rubber meets da road. */
Line 6,443 ⟶ 8,982:
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say ! /*display the factorial productproduct──►term. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error***'; say; say arg(1); say; exit 13</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the input isof: &nbsp; &nbsp; <tt> 100 </tt>}}
<pre>
100! is [158 digits]:
Line 6,457 ⟶ 8,996:
This version of the REXX program allows the use of (practically) unlimited digits.
<pre>
╔═══════════════════════════════════════════════════════════════════════════╗
║ ───── Some factorial lengths ───── ║
║ ║
║ 10 ! = 7 digits ║
║ 20 ! = 19 digits ║
║ 52 ! = 68 digits (a 1 card deck shoe.) ║
║ 104 ! = 167 digits " 2 " " " ║
║ 208 ! = 394 digits " 4 " " " ║
║ 416 ! = 911 digits " 8 " " " ║
║ ║
║ 1k ! = 2,568 digits ║
║ 10k ! = 35,660 digits ║
║ 100k ! = 456,574 digits ║
║ ║
║ 1m ! = 5,565,709 digits ║
║ 10m ! = 65,657,060 digits ║
║ 100m ! = 756,570,556 digits ║
║ ║
║ Only one result is shown below for practical reasons. ║
║ ║
║ This version of the Regina REXX interpreter is essentially limited to ║
║ around 8 million digits, but with some programming tricks, it could ║
║ yield a result up to ≈ 16 million decimal digits. ║
║ ║
║ Also, the Regina REXX interpreter is limited to an exponent of 9 ║
║ decimal digits. I.E.: 9.999...999e+999999999 ║
╚═══════════════════════════════════════════════════════════════════════════╝
</pre>
<langsyntaxhighlight lang="rexx">/*REXX program computes the factorial of a non-negativenon─negative integer, and it automatically */
/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/
numeric digits 99 /*99 digits initially, then expanded. */
Line 6,494 ⟶ 9,033:
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 1 /*define the factorial product (so far)*/
do j=2 to n; !=!*j /*compute the factorial the hard way. */
if pos(.,!)==0 then iterate /*is the ! in exponential notation? */
parse var ! 'E' digs /*extract exponent of the factorial, */
numeric digits digs+digs%10 numeric digits digs + digs % 10 /* ··· and increase it by ten percent.*/
end /*j*/ /* [↑] where da rubber meets da road. */
!= !/1 /*normalize the factorial product. */
 
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say !/1 /*normalizedisplay the factorial product. ──►term*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; exit 13</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the input isof: &nbsp; &nbsp; <tt> 1000 </tt>}}
<pre>
1000! is [2568 digits]:
Line 6,525 ⟶ 9,064:
 
This technique will allow other programs to extend their range, especially those that use decimal or floating point decimal,
<br>but can work with binary numbers as well ---─── albeit you'd most probably convert the number to decimal when a multiplier
<br>is a multiple of five [or some other method], strip the trailing zeroes, and then convert it back to binary --── although it
<br>wouldn't be necessary to convert to/from base ten for checking for trailing zeros (in decimal).
<langsyntaxhighlight lang="rexx">/*REXX program computes & shows the factorial of an integer, striping trailing zeroes. */
numeric digits 200 /*start with two hundred digits. */
parse arg N .; if N=='' then N=0 /*obtain thean optional argument from CL. */
if N=='' | N=="," then N= 0 /*Not specified? Then use the default.*/
 
!=1 1 /*define the factorial product so far. */
do j=2 to N /*compute factorial the hard way. */
old!=! ! /*save old product in case of overflow.*/
!= ! *j j /*multiple the old factorial with J. */
if pos(.,!) \==0 then do /*is the ! in exponential notation?*/
d= digits() /*D temporarily stores number digits.*/
numeric digits d+d%10 /*add 10% to the decimal digits. */
!= old! * j /*re─calculate for the "lost" digits.*/
end /*IFF ≡ if and only if. [↓] */
parse var ! '' -1 _ _ /*obtain the right-most digit of ! */
if _==0 then != strip(!, , 0) /*strip trailing zeroes IFF the ... */
end /*j*/ /* [↑] ... right-most digit is zero. */
z=0 0 /*the number of trailing zeroes in ! */
do v=5 by 0 while v<=N /*calculate number of trailing zeroes. */
z= z + N%v + N % v /*bump Z if multiple power of five.*/
v= v *5 5 /*calculate the next power of five. */
end /*v*/ /* [↑] we only advance V by ourself.*/
/*stick a fork in it, we're all done. */
 
!= ! || copies(0, z) /*add water to rehydrate the product. */
if z==0 then z= 'no' /*use gooder English for the message. */
say N'! is ['length(!) " digits with " z ' trailing zeroes]:'
say /*display blank line (for whitespace).*/
say ! /*display the factorial product. */</syntaxhighlight>
/*stick a fork in it, we're all done. */</lang>
<!-- The word ''gooder'' is a humorous use of the non-word. -->
'''{{out|output''' |text=&nbsp; when using the input isof: &nbsp; &nbsp; <tt> 100 </tt>}}
<pre>
100! is [158 digits with 24 trailing zeroes]:
Line 6,563 ⟶ 9,101:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
</pre>
'''{{out|output'''|text=&nbsp; when using the input isof: &nbsp; &nbsp; <tt> 10000 </tt>}}
 
(Output is shown at &nbsp; <big> '''<sup>4</sup>/<sub>5</sub>''' </big> &nbsp; size.)
Line 6,627 ⟶ 9,165:
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
</pre>
 
=={{header|Rhovas}}==
Solutions support arbitrarily large numbers as Rhovas's <code>Integer</code> type is arbitrary-precision (Java <code>BigInteger</code>). Additional notes:
* <code>require num >= 0;</code> asserts input range preconditions, throwing on negative numbers
 
===Iterative===
Standard iterative solution using a <code>for</code> loop:
* <code>range(2, num, :incl)</code> creates an inclusive range (<code>2 <= i <= num</code>) for iteration
 
<syntaxhighlight lang="scala">
func factorial(num: Integer): Integer {
require num >= 0;
var result = 1;
for (val i in range(2, num, :incl)) {
result = result * i;
}
return result;
}
</syntaxhighlight>
 
===Recursive===
Standard recursive solution using a pattern matching approach:
* <code>match</code> without arguments is a ''conditional match'', which works like <code>if/else</code> chains.
* Rhovas doesn't perform tail-call optimization yet, hence why this solution isn't tail recursive.
 
<syntaxhighlight lang="scala">
func factorial(num: Integer): Integer {
require num >= 0;
match {
num == 0: return 1;
else: return num * factorial(num - 1);
}
}
</syntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
give n
x = fact(n)
Line 6,635 ⟶ 9,207:
 
func fact nr if nr = 1 return 1 else return nr * fact(nr-1) ok
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
===Iterative===
<langsyntaxhighlight lang="robotic">
input string "Enter a number:"
set "in" to "('ABS('input')')"
Line 6,655 ⟶ 9,227:
* "1"
end
</syntaxhighlight>
</lang>
 
=={{header|Rockstar}}==
Here's the "minimized" Rockstar:
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Factorial takes a number
If a number is 0
Line 6,667 ⟶ 9,239:
Knock a number down
Give back the first times Factorial taking a number
</syntaxhighlight>
</lang>
 
And here's a more "idiomatic" version:
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Real Love takes a heart
A page is a memory.
Line 6,680 ⟶ 9,252:
Knock my hands down
Give back a heart of Real Love taking my hands
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
We can either directly call <code>FACT</code> or recode it in two ways:
===Iterative===
≪ '''IF''' DUP 2 < '''THEN''' DROP 1
'''ELSE'''
DUP '''WHILE''' DUP 1 > '''REPEAT''' 1 - SWAP OVER * SWAP '''END'''
DROP
'''END'''
≫ 'FACTi' STO
===Recursive===
≪ '''IF''' DUP 2 < '''THEN''' DROP 1 '''ELSE''' DUP 1 - FACTr * '''END'''
≫ 'FACTr' STO
 
69 FACT
69 FACTi
69 FACTr
{{out}}
<pre>
3: 1.71122452428E+98
2: 1.71122452428E+98
1: 1.71122452428E+98
</pre>
 
=={{header|Ruby}}==
Line 6,687 ⟶ 9,282:
* [[MRI]] does not optimize tail recursion. So factorial_tail_recursive(10000) might also fail.
 
<langsyntaxhighlight lang="ruby"># Recursive
def factorial_recursive(n)
n.zero? ? 1 : n * factorial_recursive(n - 1)
Line 6,725 ⟶ 9,320:
b.report('inject:') {m.times {factorial_inject(n)}}
b.report('reduce:') {m.times {factorial_reduce(n)}}
end</langsyntaxhighlight>
The benchmark depends on the Ruby implementation.
With [[MRI]], <code>#factorial_reduce</code> seems slightly faster than others.
Line 6,737 ⟶ 9,332:
inject: 2.500000 0.130000 2.630000 ( 2.641898)
reduce: 2.110000 0.230000 2.340000 ( 2.338166)</pre>
 
=={{header|Run BASIC}}==
<lang runbasic>for i = 0 to 100
print " fctrI(";right$("00";str$(i),2); ") = "; fctrI(i)
print " fctrR(";right$("00";str$(i),2); ") = "; fctrR(i)
next i
end
function fctrI(n)
fctrI = 1
if n >1 then
for i = 2 To n
fctrI = fctrI * i
next i
end if
end function
 
function fctrR(n)
fctrR = 1
if n > 1 then fctrR = n * fctrR(n -1)
end function</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn factorial_recursive (n: u64) -> u64 {
match n {
0 => 1,
Line 6,779 ⟶ 9,353:
}
}
</syntaxhighlight>
</lang>
 
=={{header|SASL}}==
Copied from SASL manual, page 3
<syntaxhighlight lang="sasl">
<lang SASL>
fac 4
where fac 0 = 1
fac n = n * fac (n - 1)
?
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
 
-- recursive
Line 6,810 ⟶ 9,384:
#OUT + fact(a) + " = " + fact_iter(a) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
S-BASIC's double-precision real data type supports up to 14 digits,
thereby allowing calculation up to 15! without loss of precision
<syntaxhighlight lang="BASIC">
function factorial(n=real.double)=real.double
if n = 0 then n = 1 else n = n * factorial(n-1)
end = n
 
var i=integer
print "Factorial Calculator"
print " n n!"
print "----------------------"
for i=1 to 15
print using "## #,###,###,###,###";i;factorial(i)
next i
end
</syntaxhighlight>
An iterative rather than recursive approach works equally well, if that
is your preference.
<syntaxhighlight lang="BASIC">
function factorial(n=real.double)=real.double
var i, f = real.double
f = 1
for i = 1 to n
f = f * i
next i
end = f
</syntaxhighlight>
{{out}}
<pre>
Factorial Calculator
n n!
----------------------
1 1
2 2
3 3
4 24
5 120
6 720
7 5,040
8 40,320
9 362,880
10 3,628,800
11 39,916,800
12 479,001,600
13 6,227,020,800
14 87,178,291,200
15 1,307,674,368,000
</pre>
 
 
=={{header|Scala}}==
Line 6,816 ⟶ 9,442:
===Imperative===
An imperative style using a mutable variable:
<syntaxhighlight lang ="scala">def factorial(n: Int)={
def factorial(n: Int) = {
var res = 1
for (i <- 1 to n)
res *= i
res
}
}</lang>
</syntaxhighlight>
 
===Recursive===
Using naive recursion:
<syntaxhighlight lang="scala">
<lang scala>def factorial(n: Int): Int =
def if factorial(n: == 0Int): 1Int =
if (n < 1) 1
else n * factorial(n-1)</lang>
else n * factorial(n - 1)
</syntaxhighlight>
 
Using tail recursion with a helper function:
<syntaxhighlight lang="scala">
<lang scala>def factorial(n: Int) = {
def factorial(n: Int) = {
@tailrec def fact(x: Int, acc: Int): Int = {
if (x < 2) acc else fact(x - 1, acc * x)
}
fact(n, 1)
}
}</lang>
</syntaxhighlight>
 
===Stdlib .product===
Using standard library builtin:
<langsyntaxhighlight lang="scala">
def factorial(n: Int) = (2 to n).product
</syntaxhighlight>
</lang>
 
===Folding===
Using folding:
<syntaxhighlight lang ="scala">def factorial(n: Int) =
def factorial(n: Int) =
(2 to n).foldLeft(1)(_ * _)</lang>
(2 to n).foldLeft(1)(_ * _)
</syntaxhighlight>
 
===Using implicit functions to extend the Int type===
Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:
<syntaxhighlight lang="scala">
<lang scala>implicit def IntToFac(i : Int) = new {
implicit def IntToFac(i : Int) = new {
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}
}</lang>
</syntaxhighlight>
 
{{out | Example used in the REPL}}
Line 6,865 ⟶ 9,501:
=={{header|Scheme}}==
===Recursive===
<syntaxhighlight lang ="scheme">(define (factorial n)
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))</lang>
</syntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<syntaxhighlight lang ="scheme">(define (factorial n)
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))</lang>
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang ="scheme">(define (factorial n)
(define (factorial n)
(do ((i 1 (+ i 1))
(accum 1 (* accum i)))
((> i n) accum)))</lang>
</syntaxhighlight>
 
===Folding===
<syntaxhighlight lang="scheme">
<lang scheme>;Using a generator and a function that apply generated values to a function taking two arguments
;Using a generator and a function that apply generated values to a function taking two arguments
 
;A generator knows commands 'next? and 'next
Line 6,904 ⟶ 9,549:
 
(factorial 8)
;40320</lang>
</syntaxhighlight>
 
=={{header|Scilab}}==
Line 6,910 ⟶ 9,556:
The factorial function is built-in to Scilab.
The built-in function is only accurate for <math>N \leq 21</math> due to the precision limitations of floating point numbers, but if we want to stay in integers, <math>N \leq 13</math> because <math>N! > 2^31-1</math>.
<langsyntaxhighlight Scilablang="scilab">answer = factorial(N)</langsyntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="text">function f=factoriter(n)
f=1
for i=2:n
f=f*i
end
endfunction</langsyntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="text">function f=factorrec(n)
if n==0 then f=1
else f=n*factorrec(n-1)
end
endfunction</langsyntaxhighlight>
 
===Numerical approximation===
The gamma function, <math>\Gamma(z)=\int_0^\infty t^{z-1} e^{-t}\, \mathrm{d}t \!</math>, can be used to calculate factorials, for <math>n! = \Gamma(n+1)</math>.
<syntaxhighlight lang="text">function f=factorgamma(n)
f = gamma(n+1)
endfunction</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 6,942 ⟶ 9,588:
To avoid this limitations the functions below use [http://seed7.sourceforge.net/libraries/bigint.htm bigInteger]:
===Iterative===
<langsyntaxhighlight lang="seed7">const func bigInteger: factorial (in bigInteger: n) is func
result
var bigInteger: fact is 1_;
Line 6,951 ⟶ 9,597:
fact *:= i;
end for;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#iterative_fib]
===Recursive===
<langsyntaxhighlight lang="seed7">const func bigInteger: factorial (in bigInteger: n) is func
result
var bigInteger: fact is 1_;
Line 6,962 ⟶ 9,608:
fact := n * factorial(pred(n));
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Line 6,968 ⟶ 9,614:
=={{header|Self}}==
Built in:
<syntaxhighlight lang ="self">n factorial</langsyntaxhighlight>
Iterative version:
<langsyntaxhighlight lang="self">factorial: n = (|r <- 1| 1 to: n + 1 Do: [|:i| r: r * i]. r)
</syntaxhighlight>
</lang>
Recursive version:
<langsyntaxhighlight lang="self">factorial: n = (n <= 1 ifTrue: 1 False: [n * (factorial: n predecessor)])</langsyntaxhighlight>
Factorial is product of list of numbers from 1 to n.
(Vector indexes start at 0)
<langsyntaxhighlight lang="self">factorial: n = (((vector copySize: n) mapBy: [|:e. :i| i + 1]) product)</langsyntaxhighlight>
 
=={{header|SequenceL}}==
The simplest description: factorial is the product of the numbers from 1 to n:
<langsyntaxhighlight lang="sequencel">factorial(n) := product(1 ... n);</langsyntaxhighlight>
 
Or, if you wanted to generate a list of all the factorials:
<langsyntaxhighlight lang="sequencel">factorials(n)[i] := product(1 ... i) foreach i within 1 ... n;</langsyntaxhighlight>
 
Or, written recursively:
<langsyntaxhighlight lang="sequencel">factorial: int -> int;
factorial(n) :=
1 when n <= 0
else
n * factorial(n-1);</langsyntaxhighlight>
 
Tail-recursive:
<langsyntaxhighlight lang="sequencel">factorial(n) :=
factorialHelper(1, n);
Line 6,999 ⟶ 9,645:
acc when n <= 0
else
factorialHelper(acc * n, n-1);</langsyntaxhighlight>
 
 
=={{header|SETL}}==
<langsyntaxhighlight lang="setl">$ Recursive
proc fact(n);
if (n < 2) then
Line 7,019 ⟶ 9,664:
end loop;
return v;
end proc;</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">(define factorial
0 -> 1
X -> (* X (factorial (- X 1))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
Recursive:
<langsyntaxhighlight lang="ruby">func factorial_recursive(n) {
n == 0 ? 1 : (n * __FUNC__(n-1))
}</langsyntaxhighlight>
 
Catamorphism:
<langsyntaxhighlight lang="ruby">func factorial_reduce(n) {
1..n -> reduce({|a,b| a * b }, 1)
}</langsyntaxhighlight>
 
Iterative:
<langsyntaxhighlight lang="ruby">func factorial_iterative(n) {
var f = 1
{|i| f *= i } << 2..n
return f
}</langsyntaxhighlight>
 
Built-in:
<syntaxhighlight lang ="ruby">say 5!</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="pascal">begin
integer procedure factorial(n);
integer n;
Line 7,062 ⟶ 9,707:
outint(f, 2); outint(factorial(f), 8); outimage
end
end</langsyntaxhighlight>
{{out}}
<pre>factorials:
Line 7,073 ⟶ 9,718:
=={{header|Sisal}}==
Solution using a fold:
<langsyntaxhighlight lang="sisal">define main
 
function main(x : integer returns integer)
Line 7,082 ⟶ 9,727:
end for
 
end function</langsyntaxhighlight>
Simple example using a recursive function:
<langsyntaxhighlight lang="sisal">define main
 
function main(x : integer returns integer)
Line 7,094 ⟶ 9,739:
end if
 
end function</langsyntaxhighlight>
 
=={{header|Slate}}==
This is already implemented in the core language as:
<langsyntaxhighlight lang="slate">n@(Integer traits) factorial
"The standard recursive definition."
[
Line 7,105 ⟶ 9,750:
ifTrue: [1]
ifFalse: [n * ((n - 1) factorial)]
].</langsyntaxhighlight>
Here is another way to implement it:
<langsyntaxhighlight lang="slate">n@(Integer traits) factorial2
[
n isNegative ifTrue: [error: 'Negative inputs to factorial are invalid.'].
(1 upTo: n by: 1) reduce: [|:a :b| a * b]
].</langsyntaxhighlight>
{{out}}
<pre>slate[5]> 100 factorial.
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</pre>
 
=={{header|Slope}}==
Slope supports 64 bit floating point numbers and renders ints via conversion from float.
There is no "big int" library. As such the largest integer that can be given the below
factorial procedures is 171, anything larger will produce ''+Inf''.
 
Using reduce:
<syntaxhighlight lang="slope">
(define factorial (lambda (n)
(cond
((negative? n) (! "Negative inputs to factorial are invalid"))
((zero? n) 1)
(else (reduce (lambda (num acc) (* num acc)) 1 (range n 1))))))
</syntaxhighlight>
 
Using a loop:
<syntaxhighlight lang="slope">
(define factorial (lambda (n)
(cond
((negative? n) (! "Negative inputs to factorial are invalid"))
((zero? n) 1)
(else
(for ((acc 1 (* acc i))(i 1 (+ i 1))) ((<= i n) acc))))))
</syntaxhighlight>
 
=={{header|Smalltalk}}==
Smalltalk Number class already has a <tt>factorial</tt> method; &sup1;;<br>however, let's see how we cancould implement it by ourselves.
===Iterative with fold===
{{works with|GNU Smalltalk}} {{works with|Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Number extend [
my_factorial [
(self < 2)
Line 7,131 ⟶ 9,800:
 
7 factorial printNl.
7 my_factorial printNl.</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="smalltalk">Number extend [
my_factorialfactorial [
self < 0 ifTrue: [ self error: 'my_factorialfactorial is defined for natural numbers' ].
self isZero ifTrue: [ ^1 ].
^self * ((self - 1) my_factorialfactorial)
]
].</langsyntaxhighlight>
 
===Recursive (functional)===
Defining a ''local function'' (aka closure) named 'fac':
<lang smalltalk> |fac|
<syntaxhighlight lang="smalltalk">|fac|
 
fac := [:n |
n < 0 ifTrue: [ self error: 'fac is defined for natural numbers' ].
n <= 1
ifTrue: [ 1 ]
ifFalse: [ n * (fac value:(n - 1)) ]
].
 
fac value:1000.
fac value:1000.</syntaxhighlight>
].</lang>
{{works with|Pharo|1.3-13315}}
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">| fac |
fac := [ :n | (1 to: n) inject: 1 into: [ :prod :next | prod * next ] ].
fac value: 10.
"3628800"</langsyntaxhighlight>
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">fac := [:n | (1 to: n) product].
fac value:40
-> 815915283247897734345611269596115894272000000000</langsyntaxhighlight>
 
Note &sup1;) the builtin factorial (where builtin means: ''the already provided method in the class library'') typically uses a *much* better algorithm than both the iterative and especially the recursive versions presented here. So it is a bad idea, to not use them as a programmer.
 
=={{header|SNOBOL4}}==
Line 7,168 ⟶ 9,841:
Note: Snobol4+ overflows after 7! because of signed short int limitation.
===Recursive===
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('rfact(n)') :(rfact_end)
rfact rfact = le(n,0) 1 :s(return)
rfact = n * rfact(n - 1) :(return)
rfact_end</langsyntaxhighlight>
===Tail-recursive===
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('trfact(n,f)') :(trfact_end)
trfact trfact = le(n,0) f :s(return)
trfact = trfact(n - 1, n * f) :(return)
trfact_end</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('ifact(n)') :(ifact_end)
ifact ifact = 1
if1 ifact = gt(n,0) n * ifact :f(return)
n = n - 1 :(if1)
ifact_end</langsyntaxhighlight>
Test and display factorials 0 .. 10
<langsyntaxhighlight SNOBOL4lang="snobol4">loop i = le(i,10) i + 1 :f(end)
output = rfact(i) ' ' trfact(i,1) ' ' ifact(i) :(loop)
end</langsyntaxhighlight>
{{out}}
<pre>1 1 1
Line 7,200 ⟶ 9,873:
39916800 39916800 39916800</pre>
 
=={{header|Soda}}==
 
===Recursive===
<syntaxhighlight lang="soda">
factorial (n : Int) : Int =
if n < 2
then 1
else n * factorial (n - 1)
</syntaxhighlight>
 
===Tail recursive===
<syntaxhighlight lang="soda">
_tailrec_fact (n : Int) (accum : Int) : Int =
if n < 2
then accum
else _tailrec_fact (n - 1) (n * accum)
 
factorial (n : Int) : Int =
_tailrec_fact (n) (1)
</syntaxhighlight>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "factorial n" )
@( description, "Write a function to return the factorial of a number." )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure factorial is
fact_pos : constant integer := numerics.value( $1 );
result : natural;
count : natural;
begin
if fact_pos < 0 then
put_line( standard_error, source_info.source_location & ": number must be >= 0" );
command_line.set_exit_status( 192 );
return;
end if;
if fact_pos = 0 then
? 0;
return;
end if;
result := natural( fact_pos );
count := natural( fact_pos - 1 );
for i in reverse 1..count loop
result := @ * i;
end loop;
? result;
end factorial;</syntaxhighlight>
 
=={{header|Spin}}==
Line 7,206 ⟶ 9,931:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<langsyntaxhighlight lang="spin">con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
Line 7,228 ⟶ 9,953:
repeat while n > 0
f *= n
n -= 1</langsyntaxhighlight>
{{out}}
<pre>1 1 2 6 24 120 720 5040 40320 362880 3628800 </pre>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">fact(n)=
? n!>1, <=1
<= n*fact(n-1)
.</langsyntaxhighlight>
 
=={{header|SSEM}}==
The factorial function gets large quickly: so quickly that 13! already overflows a 32-bit integer. For any real-world algorithm that may require factorials, therefore, the most economical approach on a machine comparable to the SSEM would be to store the values of 0! to 12! and simply look up the one we want. This program does that. (Note that what we actually store is the two's complement of each value: this is purely because the SSEM cannot load a number from storage without negating it, so providing the data pre-negated saves some tiresome juggling between accumulator and storage.) If word 21 holds <i>n</i>, the program will halt with the accumulator storing <i>n</i>!; as an example, we shall find 10!
<langsyntaxhighlight lang="ssem">11100000000000100000000000000000 0. -7 to c
10101000000000010000000000000000 1. Sub. 21
10100000000001100000000000000000 2. c to 5
Line 7,261 ⟶ 9,986:
00000000110101110111100110111111 19. -39916800
00000000001000001100111011000111 20. -479001600
01010000000000000000000000000000 21. 10</langsyntaxhighlight>
 
=={{header|Standard ML}}==
===Recursive===
<langsyntaxhighlight lang="sml">fun factorial n =
if n <= 0 then 1
else n * factorial (n-1)</langsyntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<langsyntaxhighlight lang="sml">fun factorial n = let
fun loop (i, accum) =
if i > n then accum
Line 7,275 ⟶ 10,000:
in
loop (1, 1)
end</langsyntaxhighlight>
 
=={{header|Stata}}==
Mata has the built-in '''factorial''' function. Here are two implementations.
 
<langsyntaxhighlight lang="stata">mata
real scalar function fact1(real scalar n) {
if (n<2) return(1)
Line 7,294 ⟶ 10,019:
printf("%f\n",fact1(8))
printf("%f\n",fact2(8))
printf("%f\n",factorial(8))</langsyntaxhighlight>
 
 
 
 
 
=={{header|SuperCollider}}==
 
===Iterative===
<syntaxhighlight lang="SuperCollider">
 
f = { |n| (1..n).product };
 
f.(10);
 
// for numbers larger than 12, use 64 bit float
// instead of 32 bit integers, because the integer range is exceeded
// (1..n) returns an array of floats when n is a float
 
f.(20.0);
 
</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="SuperCollider">
 
f = { |n| if(n < 2) { 1 } { n * f.(n - 1) } };
f.(10);
 
</syntaxhighlight>
 
 
 
 
 
=={{header|Swift}}==
===Iterative===
<langsyntaxhighlight Swiftlang="swift">func factorial(_ n: Int) -> Int {
return n < 2 ? 1 : (2...n).reduce(1, *)
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Swiftlang="swift">func factorial(_ n: Int) -> Int {
return n < 2 ? 1 : n * factorial(n - 1)
}</langsyntaxhighlight>
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
fact
if n < 1
return
endif
* n fn fn
- n
call fact
return
 
start
 
if i < 20
1 fn
i n
call fact
fn []
+ i
goif
endif
</syntaxhighlight>
 
=={{header|Tailspin}}==
===Iterative===
<syntaxhighlight lang="tailspin">
templates factorial
when <0..> do
@: 1;
1..$ -> @: $@ * $;
$@ !
end factorial
</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="tailspin">
templates factorial
when <=0> do 1 !
when <0..> $ * ($ - 1 -> factorial) !
end factorial
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 7,310 ⟶ 10,110:
Use Tcl 8.5 for its built-in arbitrary precision integer support.
===Iterative===
<langsyntaxhighlight lang="tcl">proc ifact n {
for {set i $n; set sum 1} {$i >= 2} {incr i -1} {
set sum [expr {$sum * $i}]
}
return $sum
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="tcl">proc rfact n {
expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]}
}</langsyntaxhighlight>
The recursive version is limited by the default stack size to roughly 850!
 
When put into the ''tcl::mathfunc'' namespace, the recursive call stays inside the ''expr'' language, and thus looks clearer:
<langsyntaxhighlight Tcllang="tcl">proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}}</langsyntaxhighlight>
===Iterative with caching===
<langsyntaxhighlight lang="tcl">proc ifact_caching n {
global fact_cache
if { ! [info exists fact_cache]} {
Line 7,341 ⟶ 10,141:
}
return $sum
}</langsyntaxhighlight>
===Performance Analysis===
<langsyntaxhighlight lang="tcl">puts [ifact 30]
puts [rfact 30]
puts [ifact_caching 30]
Line 7,353 ⟶ 10,153:
puts "rfact: [time {rfact $n} $iterations]"
# for the caching proc, reset the cache between each iteration so as not to skew the results
puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]"</langsyntaxhighlight>
{{out}}
<pre>265252859812191058636308480000000
Line 7,366 ⟶ 10,166:
Note that this only works correctly for factorials that produce correct representations in double precision floating-point numbers.
{{tcllib|math::special}}
<langsyntaxhighlight lang="tcl">package require math::special
 
proc gfact n {
expr {round([::math::special::Gamma [expr {$n+1}]])}
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC57}}==
The program stack has only three levels, which means that the recursive approach can be dispensed with.
TI-83 BASIC has a built-in factorial operator: x! is the factorial of x.
{| class="wikitable"
An other way is to use a combination of prod() and seq() functions:
! Machine code
<lang ti89b>10→N
! Comment
N! ---> 362880
|-
prod(seq(I,I,1,N)) ---> 362880</lang>
|
Note: maximum integer value is:
Lbl 0
13! ---> 6227020800
C.t
 
x=t
=={{header|TI-89 BASIC}}==
1
TI-89 BASIC also has the factorial function built in: x! is the factorial of x.
STO 0
<lang ti89b>factorial(x)
Lbl 1
Func
RCL 0
Return Π(y,y,1,x)
×
EndFunc</lang>
Dsz
 
GTO 1
Π is the standard product operator: <math>\overbrace{\Pi(\mathrm{expr},i,a,b)}^{\mathrm{TI-89}} = \overbrace{\prod_{i=a}^b \mathrm{expr}}^{\text{Math notation}}</math>
1
=
R/S
RST
|
program factorial(x) // x is the display register
if x=0 then
x=1
r0 = x
loop
multiply r0 by what will be in the next loop
decrement r0 and exit loop if r0 = 0
end loop
complete the multiplication sequence
return x!
end program
reset program pointer
|}
 
=={{header|TorqueScript}}==
=== Iterative ===
<langsyntaxhighlight Torquelang="torque">function Factorial(%num)
{
if(%num < 2)
Line 7,399 ⟶ 10,219:
%num *= %a;
return %num;
}</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight Torquelang="torque">function Factorial(%num)
{
if(%num < 2)
return 1;
return %num * Factorial(%num-1);
}</langsyntaxhighlight>
 
=={{header|TransFORTH}}==
<langsyntaxhighlight lang="forth">: FACTORIAL
1 SWAP
1 + 1 DO
I * LOOP ;</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
LOOP num=-1,12
IF (num==0,1) THEN
Line 7,431 ⟶ 10,251:
formatnum=CENTER(num,+2," ")
PRINT "factorial of ",formatnum," = ",f
ENDLOOP</langsyntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 7,456 ⟶ 10,276:
Via nPk function:
 
<langsyntaxhighlight lang="sh">$ txr -p '(n-perm-k 10 10)'
3628800</langsyntaxhighlight>
 
===Functional===
 
<langsyntaxhighlight lang="sh">$ txr -p '[reduce-left * (range 1 10) 1]'
3628800</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
=== Iterative ===
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">factorial() {
set -- "$1" 1
until test "$1" -lt 2; do
Line 7,473 ⟶ 10,293:
done
echo "$2"
}</langsyntaxhighlight>
 
If <code>expr</code> uses 32-bit signed integers, then this function overflows after <code>factorial 12</code>.
Line 7,481 ⟶ 10,301:
{{works with|ksh93}}
{{works with|zsh}}
<langsyntaxhighlight lang="bash">function factorial {
typeset n=$1 f=1 i
for ((i=2; i < n; i++)); do
Line 7,487 ⟶ 10,307:
done
echo $f
}</langsyntaxhighlight>
 
* bash and zsh use 64-bit signed integers, overflows after <code>factorial 20</code>.
Line 7,494 ⟶ 10,314:
These solutions fork many processes, because each level of recursion spawns a subshell to capture the output.
{{works with|Almquist Shell}}
<langsyntaxhighlight lang="bash">factorial ()
{
if [ $1 -eq 0 ]
Line 7,500 ⟶ 10,320:
else echo $(($1 * $(factorial $(($1-1)) ) ))
fi
}</langsyntaxhighlight>
 
Or in [[Korn Shell|Korn style]]:
Line 7,507 ⟶ 10,327:
{{works with|pdksh}}
{{works with|zsh}}
<langsyntaxhighlight lang="bash">function factorial {
typeset n=$1
(( n < 2 )) && echo 1 && return
echo $(( n * $(factorial $((n-1))) ))
}</langsyntaxhighlight>
==={{header|C Shell}}===
This is an iterative solution. ''csh'' uses 32-bit signed integers, so this alias overflows after <code>factorial 12</code>.
<langsyntaxhighlight lang="csh">alias factorial eval \''set factorial_args=( \!*:q ) \\
@ factorial_n = $factorial_args[2] \\
@ factorial_i = 1 \\
Line 7,526 ⟶ 10,346:
factorial f 12
echo $f
# => 479001600</langsyntaxhighlight>
 
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">Factorial = /×+1⇡</syntaxhighlight>
 
=={{header|Ursa}}==
{{trans|Python}}
===Iterative===
<langsyntaxhighlight lang="ursa">def factorial (int n)
decl int result
set result 1
Line 7,540 ⟶ 10,363:
return result
end
</syntaxhighlight>
</lang>
===Recursive===
<langsyntaxhighlight lang="ursa">def factorial (int n)
decl int z
set z 1
Line 7,549 ⟶ 10,372:
end if
return z
end</langsyntaxhighlight>
 
=={{header|Ursala}}==
There is already a library function for factorials, but they can be defined anyway like this. The good method treats natural numbers as an abstract type, and the better method factors out powers of 2 by bit twiddling.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
good_factorial = ~&?\1! product:-1^lrtPC/~& iota
better_factorial = ~&?\1! ^T(~&lSL,@rS product:-1)+ ~&Z-~^*lrtPC/~& iota</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nL
 
test = better_factorial* <0,1,2,3,4,5,6,7,8></langsyntaxhighlight>
{{out}}
<pre><1,1,2,6,24,120,720,5040,40320></pre>
 
=={{header|VBAUxntal}}==
<syntaxhighlight lang="Uxntal">@factorial ( n* -: fact* )
<lang vb>Public Function factorial(n As Integer) As Long
ORAk ?{ POP2 #0001 JMP2r }
factorial = WorksheetFunction.Fact(n)
DUP2 #0001 SUB2 factorial MUL2
End Function</lang>
JMP2r</syntaxhighlight>
 
=={{header|Verbexx}}==
<langsyntaxhighlight lang="verbexx">// ----------------
// recursive method (requires INTV_T input parm)
// ----------------
Line 7,645 ⟶ 10,470:
iterative 37! = 13763753091226345046315979581580902400000000
recursive 47! = 258623241511168180642964355153611979969197632389120000000000
iterative 47! = 258623241511168180642964355153611979969197632389120000000000</langsyntaxhighlight>
 
=={{header|Vim Script}}==
<lang vim>function! Factorial(n)
if a:n < 2
return 1
else
return a:n * Factorial(a:n-1)
endif
endfunction</lang>
 
=={{header|VBAVerilog}}==
===Recursive===
For numbers < 170 only
<syntaxhighlight lang="verilog">module main;
<lang vb>Option Explicit
function automatic [7:0] factorial;
input [7:0] i_Num;
begin
if (i_Num == 1)
factorial = 1;
else
factorial = i_Num * factorial(i_Num-1);
end
endfunction
initial
begin
$display("Factorial of 1 = %d", factorial(1));
$display("Factorial of 2 = %d", factorial(2));
$display("Factorial of 3 = %d", factorial(3));
$display("Factorial of 4 = %d", factorial(4));
$display("Factorial of 5 = %d", factorial(5));
end
endmodule</syntaxhighlight>
 
Sub Main()
Dim i As Integer
For i = 1 To 17
Debug.Print "Factorial " & i & " , recursive : " & FactRec(i) & ", iterative : " & FactIter(i)
Next
Debug.Print "Factorial 120, recursive : " & FactRec(120) & ", iterative : " & FactIter(120)
End Sub
 
Private Function FactRec(Nb As Integer) As String
If Nb > 170 Or Nb < 0 Then FactRec = 0: Exit Function
If Nb = 1 Or Nb = 0 Then
FactRec = 1
Else
FactRec = Nb * FactRec(Nb - 1)
End If
End Function
 
Private Function FactIter(Nb As Integer)
If Nb > 170 Or Nb < 0 Then FactIter = 0: Exit Function
Dim i As Integer, F
F = 1
For i = 1 To Nb
F = F * i
Next i
FactIter = F
End Function</lang>
{{out}}
<pre>Factorial 1 , recursive : 1, iterative : 1
Factorial 2 , recursive : 2, iterative : 2
Factorial 3 , recursive : 6, iterative : 6
Factorial 4 , recursive : 24, iterative : 24
Factorial 5 , recursive : 120, iterative : 120
Factorial 6 , recursive : 720, iterative : 720
Factorial 7 , recursive : 5040, iterative : 5040
Factorial 8 , recursive : 40320, iterative : 40320
Factorial 9 , recursive : 362880, iterative : 362880
Factorial 10 , recursive : 3628800, iterative : 3628800
Factorial 11 , recursive : 39916800, iterative : 39916800
Factorial 12 , recursive : 479001600, iterative : 479001600
Factorial 13 , recursive : 6227020800, iterative : 6227020800
Factorial 14 , recursive : 87178291200, iterative : 87178291200
Factorial 15 , recursive : 1307674368000, iterative : 1307674368000
Factorial 16 , recursive : 20922789888000, iterative : 20922789888000
Factorial 17 , recursive : 355687428096000, iterative : 355687428096000
Factorial 120, recursive : 6,68950291344919E+198, iterative : 6,68950291344912E+198</pre>
 
=={{header|VBScript}}==
Optimized with memoization, works for numbers up to 170 (because of the limitations on Doubles), exits if -1 is input
<lang vb>Dim lookupTable(170), returnTable(170), currentPosition, input
currentPosition = 0
 
Do While True
input = InputBox("Please type a number (-1 to quit):")
MsgBox "The factorial of " & input & " is " & factorial(CDbl(input))
Loop
 
Function factorial (x)
If x = -1 Then
WScript.Quit 0
End If
Dim temp
temp = lookup(x)
If x <= 1 Then
factorial = 1
ElseIf temp <> 0 Then
factorial = temp
Else
temp = factorial(x - 1) * x
store x, temp
factorial = temp
End If
End Function
 
Function lookup (x)
Dim i
For i = 0 To currentPosition - 1
If lookupTable(i) = x Then
lookup = returnTable(i)
Exit Function
End If
Next
lookup = 0
End Function
 
Function store (x, y)
lookupTable(currentPosition) = x
returnTable(currentPosition) = y
currentPosition = currentPosition + 1
End Function</lang>
 
=={{header|VHDL}}==
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
Line 7,824 ⟶ 10,572:
Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;
 
END Behavior ;</langsyntaxhighlight>
 
=={{header|VisualVim BasicScript}}==
<syntaxhighlight lang="vim">function! Factorial(n)
{{works with|Visual Basic|VB6 Standard}}
if a:n < 2
<lang vb>
return 1
Option Explicit
else
return a:n * Factorial(a:n-1)
Sub Main()
endif
Dim i As Variant
endfunction</syntaxhighlight>
For i = 1 To 27
Debug.Print "Factorial(" & i & ")= , recursive : " & Format$(FactRec(i), "#,###") & " - iterative : " & Format$(FactIter(i), "#,####")
Next
End Sub 'Main
Private Function FactRec(n As Variant) As Variant
n = CDec(n)
If n = 1 Then
FactRec = 1#
Else
FactRec = n * FactRec(n - 1)
End If
End Function 'FactRec
Private Function FactIter(n As Variant)
Dim i As Variant, f As Variant
f = 1#
For i = 1# To CDec(n)
f = f * i
Next i
FactIter = f
End Function 'FactIter
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Factorial(1)= , recursive : 1 - iterative : 1
Factorial(2)= , recursive : 2 - iterative : 2
Factorial(3)= , recursive : 6 - iterative : 6
Factorial(4)= , recursive : 24 - iterative : 24
Factorial(5)= , recursive : 120 - iterative : 120
Factorial(6)= , recursive : 720 - iterative : 720
Factorial(7)= , recursive : 5,040 - iterative : 5,040
Factorial(8)= , recursive : 40,320 - iterative : 40,320
Factorial(9)= , recursive : 362,880 - iterative : 362,880
Factorial(10)= , recursive : 3,628,800 - iterative : 3,628,800
Factorial(11)= , recursive : 39,916,800 - iterative : 39,916,800
Factorial(12)= , recursive : 479,001,600 - iterative : 479,001,600
Factorial(13)= , recursive : 6,227,020,800 - iterative : 6,227,020,800
Factorial(14)= , recursive : 87,178,291,200 - iterative : 87,178,291,200
Factorial(15)= , recursive : 1,307,674,368,000 - iterative : 1,307,674,368,000
Factorial(16)= , recursive : 20,922,789,888,000 - iterative : 20,922,789,888,000
Factorial(17)= , recursive : 355,687,428,096,000 - iterative : 355,687,428,096,000
Factorial(18)= , recursive : 6,402,373,705,728,000 - iterative : 6,402,373,705,728,000
Factorial(19)= , recursive : 121,645,100,408,832,000 - iterative : 121,645,100,408,832,000
Factorial(20)= , recursive : 2,432,902,008,176,640,000 - iterative : 2,432,902,008,176,640,000
Factorial(21)= , recursive : 51,090,942,171,709,440,000 - iterative : 51,090,942,171,709,440,000
Factorial(22)= , recursive : 1,124,000,727,777,607,680,000 - iterative : 1,124,000,727,777,607,680,000
Factorial(23)= , recursive : 25,852,016,738,884,976,640,000 - iterative : 25,852,016,738,884,976,640,000
Factorial(24)= , recursive : 620,448,401,733,239,439,360,000 - iterative : 620,448,401,733,239,439,360,000
Factorial(25)= , recursive : 15,511,210,043,330,985,984,000,000 - iterative : 15,511,210,043,330,985,984,000,000
Factorial(26)= , recursive : 403,291,461,126,605,635,584,000,000 - iterative : 403,291,461,126,605,635,584,000,000
Factorial(27)= , recursive : 10,888,869,450,418,352,160,768,000,000 - iterative : 10,888,869,450,418,352,160,768,000,000
 
=={{header|V (Vlang)}}==
Updated to V (Vlang) version 0.2.2
===Imperative===
<syntaxhighlight lang="go">const max_size = 10
 
fn factorial_i() {
</pre>
mut facs := [0].repeat(max_size + 1)
facs[0] = 1
println('The 0-th Factorial number is: 1')
for i := 1; i <= max_size; i++ {
facs[i] = i * facs[i - 1]
num := facs[i]
println('The $i-th Factorial number is: $num')
}
}
 
fn main() {
=={{header|Visual Basic .NET}}==
factorial_i()
{{trans|C#}}
}</syntaxhighlight>
{{libheader|System.Numerics}}
Various type implementations follow. No error checking, so don't try to evaluate a number less than zero, or too large of a number.
<lang vbnet>Imports System
Imports System.Numerics
Imports System.Linq
 
===Recursive===
Module Module1
<syntaxhighlight lang="go">const max_size = 10
 
fn factorial_r(n int) int {
' Type Double:
if n == 0 {
return 1
}
return n * factorial_r(n - 1)
}
 
fn main() {
Function DofactorialI(n As Integer) As Double ' Iterative
for i := 0; i <= max_size; i++ {
DofactorialI = 1 : For i As Integer = 1 To n : DofactorialI *= i : Next
println('factorial($i) is: ${factorial_r(i)}')
End Function
}
}</syntaxhighlight>
 
===Tail Recursive===
' Type Unsigned Long:
<syntaxhighlight lang="go">const max_size = 10
 
fn factorial_tail(n int) int {
Function ULfactorialI(n As Integer) As ULong ' Iterative
sum := 1
ULfactorialI = 1 : For i As Integer = 1 To n : ULfactorialI *= i : Next
return factorial_r(n, sum)
End Function
}
 
fn factorial_r(n int, sum int) int {
' Type Decimal:
if n == 0 {
 
return sum
Function DefactorialI(n As Integer) As Decimal ' Iterative
}
DefactorialI = 1 : For i As Integer = 1 To n : DefactorialI *= i : Next
return factorial_r(n - 1, n * sum )
End Function
 
' Extends precision by "dehydrating" and "rehydrating" the powers of ten
Function DxfactorialI(n As Integer) As String ' Iterative
Dim factorial as Decimal = 1, zeros as integer = 0
For i As Integer = 1 To n : factorial *= i
If factorial Mod 10 = 0 Then factorial /= 10 : zeros += 1
Next : Return factorial.ToString() & New String("0", zeros)
End Function
 
' Arbitrary Precision:
 
Function FactorialI(n As Integer) As BigInteger ' Iterative
factorialI = 1 : For i As Integer = 1 To n : factorialI *= i : Next
End Function
 
Function Factorial(number As Integer) As BigInteger ' Functional
Return Enumerable.Range(1, number).Aggregate(New BigInteger(1),
Function(acc, num) acc * num)
End Function
 
Sub Main()
Console.WriteLine("Double : {0}! = {1:0}", 20, DoFactorialI(20))
Console.WriteLine("ULong : {0}! = {1:0}", 20, ULFactorialI(20))
Console.WriteLine("Decimal : {0}! = {1:0}", 27, DeFactorialI(27))
Console.WriteLine("Dec.Ext : {0}! = {1:0}", 32, DxFactorialI(32))
Console.WriteLine("Arb.Prec: {0}! = {1}", 250, Factorial(250))
End Sub
End Module</lang>
{{out}}
Note that the first four are the maximum possible for their type without causing a run-time error.
<pre>Double : 20! = 2432902008176640000
ULong : 20! = 2432902008176640000
Decimal : 27! = 10888869450418352160768000000
Dec.Ext : 32! = 263130836933693530167218012160000000
Arb.Prec: 250! = 3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000
</pre>
 
=={{header|Vlang}}==
Imperative solution:
<lang Vlang>
const (
MAX = 10
)
 
fn main() {
mut facs := [1; MAX+1]
facs[0] = 1
println('The 0-th Factorial number is: 1')
for i:= 1; i <= MAX; i++ {
facs[i] = i * facs[i-1]
num := facs[i]
println('The $i-th Factorial number is: $num')
}
}
</lang>
 
Recursive solution:
<lang Vlang>
const (
MAX = 10
)
 
fn main() {
for i := 0; i <= MAXmax_size; i++ {
println('factorial($i) is: ${facfactorial_tail(i)}')
}
}</syntaxhighlight>
}
 
===Memoized===
fn fac(n int) int {
<syntaxhighlight lang="go">const max_size = 10
if n == 0 {
return 1
}
return n * fac(n - 1)
}
</lang>
 
Memoized solution:
<lang Vlang>
const (
MAX = 10
)
 
struct Cache {
mut:
values []int
}
 
fn fac_cached(n int, cache mut cache Cache) int {
is_in_cache := cache.values.len > n
if is_in_cache {
return cache.values[n]
}
fac_n := if n == 0 { 1 } else { n * fac_cached(n - 1, mut cache) }
 
fac_n := if n == 0 {
1
} else {
n * fac_cached(n - 1, mut cache)
}
 
cache.values << fac_n
 
return fac_n
}
 
fn main() {
mut ccache := Cache{}
for n := 0; n <= MAXmax_size; n++ {
fac_n := fac_cached(n, mut ccache)
println('The $n-th Factorial is: $fac_n')
}
}</syntaxhighlight>
}
{{out}}
</lang>
<pre>The 0-th Factorial is: 1
The 1-th Factorial is: 1
The 2-th Factorial is: 2
The 3-th Factorial is: 6
The 4-th Factorial is: 24
The 5-th Factorial is: 120
The 6-th Factorial is: 720
The 7-th Factorial is: 5040
The 8-th Factorial is: 40320
The 9-th Factorial is: 362880
The 10-th Factorial is: 3628800</pre>
 
=={{header|Wart}}==
 
===Recursive, all at once===
<langsyntaxhighlight lang="python">def (fact n)
if (n = 0)
1
(n * (fact n-1))</langsyntaxhighlight>
 
===Recursive, using cases and pattern matching===
<langsyntaxhighlight lang="python">def (fact n)
(n * (fact n-1))
 
def (fact 0)
1</langsyntaxhighlight>
 
===Iterative, with an explicit loop===
<langsyntaxhighlight lang="python">def (fact n)
ret result 1
for i 1 (i <= n) ++i
result <- result*i</langsyntaxhighlight>
 
===Iterative, with a pseudo-generator===
<langsyntaxhighlight lang="python"># a useful helper to generate all the natural numbers until n
def (nums n)
collect+for i 1 (i <= n) ++i
Line 8,058 ⟶ 10,706:
 
def (fact n)
(reduce (*) nums.n 1)</langsyntaxhighlight>
 
=={{header|WDTE}}==
 
===Recursive===
<syntaxhighlight lang="wdte">let max a b => a { < b => b };
 
let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1;</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="wdte">let s => import 'stream';
 
let ! n => s.range 1 (+ n 1) -> s.reduce 1 *;</syntaxhighlight>
 
=={{header|WebAssembly}}==
 
<syntaxhighlight lang="webassembly">
<lang WebAssembly>
(module
;; recursive
(func $fac (param f64) (result f64)
get_local 0
Line 8,079 ⟶ 10,740:
end)
(export "fac" (func $fac)))
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="webassembly">
=={{header|WDTE}}==
(module
;; recursive, more compact version
(func $fac_f64 (export "fac_f64") (param f64) (result f64)
get_local 0 f64.const 1 f64.lt
if (result f64)
f64.const 1
else
get_local 0
get_local 0 f64.const 1 f64.sub
call $fac_f64
f64.mul
end
)
)
</syntaxhighlight>
 
<syntaxhighlight lang="webassembly">
===Recursive===
(module
<lang WDTE>let max a b => a { < b => b };
;; recursive, refactored to use s-expressions
(func $fact_f64 (export "fact_f64") (param f64) (result f64)
(if (result f64) (f64.lt (get_local 0) (f64.const 1))
(then f64.const 1)
(else
(f64.mul
(get_local 0)
(call $fact_f64 (f64.sub (get_local 0) (f64.const 1)))
)
)
)
)
)
</syntaxhighlight>
 
<syntaxhighlight lang="webassembly">
let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1;</lang>
(module
;; recursive, refactored to use s-expressions and named variables
(func $fact_f64 (export "fact_f64") (param $n f64) (result f64)
(if (result f64) (f64.lt (get_local $n) (f64.const 1))
(then f64.const 1)
(else
(f64.mul
(get_local $n)
(call $fact_f64 (f64.sub (get_local $n) (f64.const 1)))
)
)
)
)
)
</syntaxhighlight>
 
<syntaxhighlight lang="webassembly">
===Iterative===
(module
<lang WDTE>let s => import 'stream';
;; iterative, generated by C compiler (LLVM) from recursive code!
 
(func $factorial (export "factorial") (param $p0 i32) (result i32)
let ! n => s.range 1 (+ n 1) -> s.reduce 1 *;</lang>
(local $l0 i32) (local $l1 i32)
block $B0
get_local $p0
i32.eqz
br_if $B0
i32.const 1
set_local $l0
loop $L1
get_local $p0
get_local $l0
i32.mul
set_local $l0
get_local $p0
i32.const -1
i32.add
tee_local $l1
set_local $p0
get_local $l1
br_if $L1
end
get_local $l0
return
end
i32.const 1
)
)
</syntaxhighlight>
 
=={{header|Wortel}}==
Operator:
<syntaxhighlight lang ="wortel">@fac 10</langsyntaxhighlight>
Number expression:
<syntaxhighlight lang ="wortel">!#~F 10</langsyntaxhighlight>
Folding:
<langsyntaxhighlight lang="wortel">!/^* @to 10
; or
@prod @to 10</langsyntaxhighlight>
Iterative:
<langsyntaxhighlight lang="wortel">~!10 &n [
@var r 1
@for x to n
:!*r x
r
]</langsyntaxhighlight>
Recursive:
<langsyntaxhighlight lang="wortel">@let {
fac &{fac n}?{
<n 2 n
Line 8,123 ⟶ 10,855:
 
[[!fac 10 !facM 10]]
}</langsyntaxhighlight>
 
=={{header|Wrapl}}==
===Product===
<langsyntaxhighlight lang="wrapl">DEF fac(n) n <= 1 | PROD 1:to(n);</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="wrapl">DEF fac(n) n <= 0 => 1 // n * fac(n - 1);</langsyntaxhighlight>
===Folding===
<langsyntaxhighlight lang="wrapl">DEF fac(n) n <= 1 | :"*":foldl(ALL 1:to(n));</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./big" for BigInt
 
class Factorial {
static iterative(n) {
if (n < 2) return BigInt.one
var fact = BigInt.one
for (i in 2..n.toSmall) fact = fact * i
return fact
}
 
static recursive(n) {
if (n < 2) return BigInt.one
return n * recursive(n-1)
}
}
 
var n = BigInt.new(24)
Fmt.print("Factorial(%(n)) iterative -> $,s", Factorial.iterative(n))
Fmt.print("Factorial(%(n)) recursive -> $,s", Factorial.recursive(n))</syntaxhighlight>
 
{{out}}
<pre>
Factorial(24) iterative -> 620,448,401,733,239,439,360,000
Factorial(24) recursive -> 620,448,401,733,239,439,360,000
</pre>
 
=={{header|x86 Assembly}}==
{{works with|nasm}}
===Iterative===
<langsyntaxhighlight lang="asm">global factorial
section .text
 
Line 8,146 ⟶ 10,908:
mul ecx
loop .factor
ret</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="asm">global fact
section .text
 
Line 8,167 ⟶ 10,929:
; base case: return 1
mov eax, 1
ret</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="asm">global factorial
section .text
 
Line 8,185 ⟶ 10,947:
mul ecx ; accumulator *= n
dec ecx ; n -= 1
jmp .base_case ; tail call</langsyntaxhighlight>
 
=={{header|XL}}==
<langsyntaxhighlight XLlang="xl">0! -> 1
N! -> N * (N-1)!</langsyntaxhighlight>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun factorial (x)
(if (< x 0)
nil
(if (<= x 1)
1
(* x (factorial (- x 1))) ) ) )</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func FactIter(N); \Factorial of N using iterative method
int N; \range: 0..12
int F, I;
Line 8,210 ⟶ 10,972:
func FactRecur(N); \Factorial of N using recursive method
int N; \range: 0..12
return if N<2 then 1 else N*FactRecur(N-1);</langsyntaxhighlight>
 
=={{header|YabasicYAMLScript}}==
<syntaxhighlight lang="yaml">
<lang Yabasic>// recursive
#!/usr/bin/env ys-0
sub factorial(n)
if n > 1 then return n * factorial(n - 1) else return 1 end if
end sub
 
defn main(n):
//iterative
say: "$n! = $factorial(n)"
sub factorial2(n)
local i, t
t = 1
for i = 1 to n
t = t * i
next
return t
end sub
 
defn factorial(x):
for n = 0 to 9
apply *: 2 .. x
print "Factorial(", n, ") = ", factorial(n)
</syntaxhighlight>
next</lang>
 
=={{header|Zig}}==
{{Works with|Zig|0.11.0}}
Supports all integer data types, and checks for both overflow and negative numbers; returns null when there is a domain error.
<syntaxhighlight lang="zig">
pub fn factorial(comptime Num: type, n: i8) ?Num {
return if (@typeInfo(Num) != .Int)
@compileError("factorial called with non-integral type: " ++ @typeName(Num))
else if (n < 0)
null
else calc: {
var i: i8 = 1;
var fac: Num = 1;
while (i <= n) : (i += 1) {
const tmp = @mulWithOverflow(fac, i);
if (tmp[1] != 0)
break :calc null; // overflow
fac = tmp[0];
} else break :calc fac;
};
}
 
pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
 
try stdout.print("-1! = {?}\n", .{factorial(i32, -1)});
try stdout.print("0! = {?}\n", .{factorial(i32, 0)});
try stdout.print("5! = {?}\n", .{factorial(i32, 5)});
try stdout.print("33!(64 bit) = {?}\n", .{factorial(i64, 33)}); // not valid i64 factorial
try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible
try stdout.print("34! = {?}\n", .{factorial(i128, 34)}); // will overflow
}
</syntaxhighlight>
{{Out}}
<pre>
-1! = null
0! = 1
5! = 120
33!(64 bit) = null
33! = 8683317618811886495518194401280000000
34! = null
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn fact(n){[2..n].reduce('*,1)}
fcn factTail(n,N=1) { // tail recursion
if (n == 0) return(N);
return(self.fcn(n-1,n*N));
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fact(6).println();
var BN=Import("zklBigNum");
factTail(BN(42)) : "%,d".fmt(_).println(); // built in as BN(42).factorial()</langsyntaxhighlight>
{{out}}
<pre>
Line 8,248 ⟶ 11,042:
</pre>
The [..] notation understands int, float and string but not big int so fact(BN) doesn't work but tail recursion is just a loop so the two versions are pretty much the same.
 
=={{header|ZX Spectrum Basic}}==
===Iterative===
<lang zxbasic>10 LET x=5: GO SUB 1000: PRINT "5! = ";r
999 STOP
1000 REM *************
1001 REM * FACTORIAL *
1002 REM *************
1010 LET r=1
1020 IF x<2 THEN RETURN
1030 FOR i=2 TO x: LET r=r*i: NEXT i
1040 RETURN </lang>
{{out}}
<pre>
5! = 120
</pre>
 
===Recursive===
Using VAL for delayed evaluation and AND's ability to return given string or empty,
we can now control the program flow within an expression in a manner akin to LISP's cond:
<lang zxbasic>DEF FN f(n) = VAL (("1" AND n<=0) + ("n*FN f(n-1)" AND n>0)) </lang>
But, truth be told, the parameter n does not withstand recursive calling.
Changing the order of the product gives naught:
<lang zxbasic>DEF FN f(n) = VAL (("1" AND n<=0) + ("FN f(n-1)*n" AND n>0))</lang>
18

edits