Factorial: Difference between revisions

163,176 bytes added ,  14 days ago
Add Uiua as a solution
m (Change name of result.)
(Add Uiua as a solution)
(465 intermediate revisions by more than 100 users not shown)
Line 1:
{{task|Arithmetic operations}}
[[Category:Recursion]]
[[Category:Memoization]][[Category:Classic CS problems and programs]]
[[Category:Classic CS problems and programs]]
[[Category:Arithmetic]]
[[Category:Simple]]
 
;Definitions:
:*   The factorial of   '''0'''   (zero)   is [[wp:Factorial#Definition|defined]] as being   1   (unity).
:* &nbsp; The &nbsp; '''Factorial Function''' &nbsp; of a positive integer, &nbsp; <big> ''n'', </big> &nbsp; is defined as the product of the sequence:
<big><big> ''n'', &nbsp; ''n''-1, &nbsp; ''n''-2, &nbsp; ... &nbsp; 1 </big></big>
:* &nbsp; The factorial of &nbsp; '''0''' &nbsp; (zero) &nbsp; is [[wp:Factorial#Definition|defined]] as being &nbsp; 1 &nbsp; (unity).
 
 
Line 17 ⟶ 18:
 
Support for trapping negative &nbsp; <big> ''n'' </big> &nbsp; errors is optional.
 
 
;Related task:
* &nbsp; [[Primorial numbers]]
<br><br>
 
Line 22 ⟶ 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 32 ⟶ 37:
{+% Dequeue incidental 0, add to get Y into Z, output fac(n).
<:a:~$ Output a newline.
^:r:</langsyntaxhighlight>
 
{{out}}
Line 42 ⟶ 47:
78
2d0</pre>
 
=={{header|11l}}==
 
<syntaxhighlight lang="11l">F factorial(n)
V result = 1
L(i) 2..n
result *= i
R result
 
L(n) 0..5
print(n‘ ’factorial(n))</syntaxhighlight>
 
{{out}}
<pre>
0 1
1 1
2 2
3 6
4 24
5 120
</pre>
 
=={{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 60 ⟶ 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 85 ⟶ 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 108 ⟶ 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 121 ⟶ 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 133 ⟶ 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 147 ⟶ 446:
 
return fact;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="actionscript">public static function factorial(n:int):int
{
if (n < 0)
Line 158 ⟶ 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 170 ⟶ 469:
end loop;
return Result;
end Factorial;</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="ada">function Factorial(N : Positive) return Positive is
Result : Positive := 1;
begin
Line 179 ⟶ 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 242 ⟶ 541:
New_Line;
end loop;
end Factorial_Numeric_Approximation;</langsyntaxhighlight>
{{out}}
<pre>
Line 257 ⟶ 556:
factorial( 9) = (362880.00000000, 0.00000000)
</pre>
 
=={{header|Agda}}==
<syntaxhighlight lang="agda">module Factorial where
 
open import Data.Nat using (ℕ ; zero ; suc ; _*_)
 
factorial : (n : ℕ) → ℕ
factorial zero = 1
factorial (suc n) = (suc n) * (factorial n)
</syntaxhighlight>
 
=={{header|Aime}}==
===Iterative===
<langsyntaxhighlight lang="aime">integer
factorial(integer n)
{
Line 273 ⟶ 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 287 ⟶ 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 317 ⟶ 647:
OD
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 333 ⟶ 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 339 ⟶ 669:
n*factorial(n-1)
ESAC
; ~</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
Iterative solution
<langsyntaxhighlight lang="algolw">begin
% computes factorial n iteratively %
integer procedure factorial( integer value n ) ;
Line 357 ⟶ 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 391 ⟶ 731:
}
return ans;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="apex">public static long factRec(final Integer n) {
if (n < 0){
System.debug('No negative numbers');
Line 399 ⟶ 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 420 ⟶ 767:
end repeat
return R
end factorial</langsyntaxhighlight>
 
===Recursion===
Line 427 ⟶ 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 '''foldl(product, 1, range(enumFromTo(1, x))''',
where product is defined in terms of a fold.
 
<lang AppleScript>-- product :: Int -> Int ->Int
on product(a, b)
a * b
end product
 
<syntaxhighlight lang="applescript">------------------------ FACTORIAL -----------------------
 
-- factorial :: Int -> Int
on factorial(x)
foldl(product, 1, range(enumFromTo(1, x))
end factorial
 
 
--------------------------- TEST -------------------------
on run
factorial(11)
--> 39916800
end run
 
 
-------------------- GENERIC FUNCTIONS -------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set xs to {}
repeat with i from m to n
set end of xs to i
end repeat
xs
else
{}
end if
end enumFromTo
 
-- GENERIC LIBRARY PRIMITIVES
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 464 ⟶ 829:
set lng to length of xs
repeat with i from 1 to lng
set v to lambda|λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- range :: Int -> Int -> [Int]
on range(m, n)
if n < m then
set d to -1
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 range
 
 
Line 492 ⟶ 843:
else
script
property lambda|λ| : f
end script
end if
end mReturn</lang>
 
=={{header|Applesoft BASIC}}==
===Iterative===
<lang ApplesoftBasic>100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END
 
-- product :: [Num] -> Num
200 N = INT(N)
on product(xs)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
script multiply
220 RETURN</lang>
on |λ|(a, b)
===Recursive===
a * b
<lang ApplesoftBasic> 10 A = 768:L = 7
end |λ|
20 DATA 165,157,240,3
end script
30 DATA 32,149,217,96
40 FOR I = A TO A + L
foldl(multiply, 1, xs)
50 READ B: POKE I,B: NEXT
end product</syntaxhighlight>
60 H = 256: POKE 12,A / H
{{Out}}
70 POKE 11,A - PEEK (12) * H
<pre>39916800</pre>
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 528 ⟶ 873:
}
</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program factorial.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLargeNumber: .asciz "Number N to large. \n"
szMessNegNumber: .asciz "Number N is negative. \n"
 
szMessResult: .ascii "Resultat = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
 
mov r0,#-5
bl factorial
mov r0,#10
bl factorial
mov r0,#20
bl factorial
 
 
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
 
 
/********************************************/
/* calculation */
/********************************************/
/* r0 contains number N */
factorial:
push {r1,r2,lr} @ save registres
cmp r0,#0
blt 99f
beq 100f
cmp r0,#1
beq 100f
bl calFactorial
cmp r0,#-1 @ overflow ?
beq 98f
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
b 100f
 
98: @ display error message
ldr r0,iAdrszMessLargeNumber
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessNegNumber
bl affichageMess
 
100:
pop {r1,r2,lr} @ restaur registers
bx lr @ return
iAdrszMessNegNumber: .int szMessNegNumber
iAdrszMessLargeNumber: .int szMessLargeNumber
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* calculation */
/******************************************************************/
/* r0 contains the number N */
calFactorial:
cmp r0,#1 @ N = 1 ?
bxeq lr @ yes -> return
push {fp,lr} @ save registers
sub sp,#4 @ 4 byte on the stack
mov fp,sp @ fp <- start address stack
str r0,[fp] @ fp contains N
sub r0,#1 @ call function with N - 1
bl calFactorial
cmp r0,#-1 @ error overflow ?
beq 100f @ yes -> return
ldr r1,[fp] @ load N
umull r0,r2,r1,r0 @ multiply result by N
cmp r2,#0 @ r2 is the hi rd if <> 0 overflow
movne r0,#-1 @ if overflow -1 -> r0
 
100:
add sp,#4 @ free 4 bytes on stack
pop {fp,lr} @ restau2 registers
bx lr @ return
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} /* save registers */
mov r3,r1
mov r2,#10
 
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaves in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
 
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
 
=={{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="rebol">factorial: $[n][
if? n>0 [n * factorial n-1]
else [1]
]</syntaxhighlight>
 
===Fold===
 
<syntaxhighlight lang="rebol">factorial: $[n][
fold.seed:1 1..n [a,b][a*b]
]</syntaxhighlight>
 
===Product===
 
<syntaxhighlight lang="rebol">factorial: $[n][product 1..n]
 
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">
/---------*--~-$#-&
| /--;---\| [!]-\
| *------++--*#1/
| | /1#\ ||
[*]*{-}-*~<+*?#-.
*-------+-</
\-#0----/
</syntaxhighlight>
 
=={{header|ATS}}==
 
===Iterative===
<syntaxhighlight lang="ats">
<lang ATS>
fun
fact
Line 543 ⟶ 1,150:
val () = while (n > 0) (res := res * n; n := n - 1)
}
</syntaxhighlight>
</lang>
 
===Recursive===
<syntaxhighlight lang="ats">
<lang ATS>
fun
factorial
Line 552 ⟶ 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 564 ⟶ 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 576 ⟶ 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 599 ⟶ 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 610 ⟶ 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 629 ⟶ 1,263:
}
return r
}</langsyntaxhighlight>
 
=={{header|Axe}}==
'''Iterative'''
<langsyntaxhighlight lang="axe">Lbl FACT
1→R
For(I,1,r₁)
Line 639 ⟶ 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 659 ⟶ 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 672 ⟶ 1,305:
{1 }{ dup 1 - fact ! *})
cond}))
</syntaxhighlight>
</lang>
 
When run, either code snippet generates the following
Line 691 ⟶ 1,324:
=={{header|bash}}==
===Recursive===
<langsyntaxhighlight lang="bash">factorial()
{
if [ $1 -le 1 ]
Line 701 ⟶ 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 714 ⟶ 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 725 ⟶ 1,376:
factorial = n * factorial(n-1)
END IF
END FUNCTION</langsyntaxhighlight>
 
==={{header|BASIC256Applesoft BASIC}}===
====Iterative====
<syntaxhighlight lang="applesoftbasic">100 N = 4 : GOSUB 200"FACTORIAL
<lang BASIC256>print "enter a number, n = ";
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))
Line 740 ⟶ 1,431:
next p
end if
end function</langsyntaxhighlight>
 
====Recursive====
<langsyntaxhighlight BASIC256lang="basic256">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
Line 753 ⟶ 1,444:
factorial = 1
end if
end function</langsyntaxhighlight>
 
==={{header|BatchBBC FileBASIC}}===
<lang dos>@echo off
set /p x=
set /a fs=%x%-1
set y=%x%
FOR /L %%a IN (%fs%, -1, 1) DO SET /a y*=%%a
if %x% EQU 0 set y=1
echo %y%
pause
exit</lang>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
18! is the largest that doesn't overflow.
<langsyntaxhighlight lang="bbcbasic"> *FLOAT64
@% = &1010
Line 776 ⟶ 1,456:
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)</langsyntaxhighlight>
{{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}}===
All numbers in Commodore BASIC are stored as floating-point with a 32-bit mantissa. The maximum representable value is 1.70141183 × 10<sup>38</sup>, so it can handle factorials up to 33! = 8.68331762 × 10<sup>36</sup>, but only keeps 32 bits of precision. That means that what you see is what you get; the mantissa for 33! is 8.68331762 exactly instead of 8.68331761881188649551819440128.
 
====Iterative====
<syntaxhighlight lang="freebasic">10 REM FACTORIAL
20 REM COMMODORE BASIC 2.0
30 INPUT "N=";N: GOSUB 100
40 PRINT N;"! =";F
50 GOTO 30
100 REM FACTORIAL CALC USING SIMPLE LOOP
110 F = 1
120 FOR I=1 TO N
130 F = F*I
140 NEXT
150 RETURN</syntaxhighlight>
 
====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
110 DIM F(35): F(0)=1: REM MEMOS
120 DIM S(35): SP=0: REM STACK+PTR
130 FOR I=1 TO 13
140 : S(SP)=I: SP=SP+1: REM PUSH(I)
150 : GOSUB 200
160 : SP=SP-1: REM POP
170 : PRINT I;"! = ";S(SP)
180 NEXT I
190 END
200 REM FACTORIAL: S(SP-1) = S(SP-1)!
210 IF F(S(SP-1)) THEN 240: REM MEMOIZED
220 S(SP)=S(SP-1)-1: SP=SP+1: GOSUB 200: REM RECURSE
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</syntaxhighlight>
 
{{Out}}
<pre> 1 ! = 1
2 ! = 2
3 ! = 6
4 ! = 24
5 ! = 120
6 ! = 720
7 ! = 5040
8 ! = 40320
9 ! = 362880
10 ! = 3628800
11 ! = 39916800
12 ! = 479001600
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}}===
<syntaxhighlight lang="is-basic">100 DEF FACT(N)
110 LET F=1
120 FOR I=2 TO N
130 LET F=F*I
140 NEXT
150 LET FACT=F
160 END DEF</syntaxhighlight>
 
==={{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====
<syntaxhighlight 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</syntaxhighlight>
{{in}}
<pre>13</pre>
{{out}}
<pre>6227020800</pre>
====Recursive====
A <code>GOSUB</code> is just a procedure call that doesn't pass parameters.
<syntaxhighlight lang="basic"> 10 INPUT N
20 LET FACT=1
30 GOSUB 60
40 PRINT FACT
50 STOP
60 IF N=0 THEN RETURN
70 LET FACT=FACT*N
80 LET N=N-1
90 GOSUB 60
100 RETURN</syntaxhighlight>
{{in}}
<pre>13</pre>
{{out}}
<pre>6227020800</pre>
 
==={{header|TI-83 BASIC}}===
TI-83 BASIC has a built-in factorial operator: x! is the factorial of x.
An other way is to use a combination of prod() and seq() functions:
<syntaxhighlight lang="ti89b">10→N
N! ---> 362880
prod(seq(I,I,1,N)) ---> 362880</syntaxhighlight>
Note: maximum integer value is:
13! ---> 6227020800
 
==={{header|TI-89 BASIC}}===
TI-89 BASIC also has the factorial function built in: x! is the factorial of x.
<syntaxhighlight lang="ti89b">factorial(x)
Func
Return Π(y,y,1,x)
EndFunc</syntaxhighlight>
 
Π 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>
 
==={{Header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 LET F = 1
20 PRINT "Enter an integer."
30 INPUT N
40 IF N = 0 THEN GOTO 80
50 LET F = F * N
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}}==
<syntaxhighlight lang="dos">@echo off
set /p x=
set /a fs=%x%-1
set y=%x%
FOR /L %%a IN (%fs%, -1, 1) DO SET /a y*=%%a
if %x% EQU 0 set y=1
echo %y%
pause
exit</syntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">#! /usr/bin/bc -q
 
define f(x) {
Line 787 ⟶ 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 794 ⟶ 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 810 ⟶ 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 822 ⟶ 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 860 ⟶ 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 871 ⟶ 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 885 ⟶ 2,428:
Lastly, here is an iterative solution
 
<langsyntaxhighlight lang="bracmat">(factorial=
r
. !arg:?r
Line 891 ⟶ 2,434:
' (!arg:>1&(!arg+-1:?arg)*!r:?r)
& !r
);</langsyntaxhighlight>
 
factorial$5000
Line 898 ⟶ 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 912 ⟶ 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 921 ⟶ 2,476:
Following examples display other ways to calculate the factorial function:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 1 6r@pd
720
Line 934 ⟶ 2,489:
blsq ) 7ro)(.*){0 1 11}die!
720
</syntaxhighlight>
</lang>
 
=={{header|C}}==
 
=={{header|embedded C for AVR MCU}}==
=== Iterative ===
<langsyntaxhighlight lang="c">longint factorial(int n) {
longint result = 1;
for (int i = 1; i <= n; ++i)
do {
result *= ni;
while(--n);
return result;
}
}</lang>
</syntaxhighlight>
 
Handle negative n (returning -1)
=={{header|C}}==
 
=== Iterative ===
<langsyntaxhighlight lang="c">int factorialfactorialSafe(int n) {
int result = 1;
if(n<0)
return -1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
}</lang>
</syntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang="c">int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
}</lang>
</syntaxhighlight>
 
Handle negative n (returning -1).
 
<syntaxhighlight lang="c">int factorialSafe(int n) {
return n<0 ? -1 : n == 0 ? 1 : n * factorialSafe(n - 1);
}
</syntaxhighlight>
 
=== 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);
}
 
int fac_auxSafe(int n, int acc) {
return n<0 ? -1 : n < 1 ? acc : fac_aux(n - 1, acc * n);
}
 
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">
#include <stdio.h>
 
#define l11l 0xFFFF
#define ll1 for
#define ll111 if
#define l1l1 unsigned
#define l111 struct
#define lll11 short
#define ll11l long
#define ll1ll putchar
#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1;
#define l1ll1 *lllll++=l1ll%10000;l1ll/=10000;
#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\
lllll=(l1=l1->lll1l)->lll;ll=1-1;
#define llll 1000
 
 
 
 
l111 llll1 {
l111 llll1 *
lll1l,*ll1l1 ;l1l1 lll11 lll [
llll];};main (){l111 llll1 *ll11,*l1l,*
l1, *ll1l, * malloc ( ) ; l1l1 ll11l l1ll ;
ll11l l11,ll ,l;l1l1 lll11 *lll1,* lllll; ll1(l
=1-1 ;l< 14; ll1ll("\t\"8)>l\"9!.)>vl" [l]^'L'),++l
);scanf("%d",&l);l1l1l(l1l) l1l1l(ll11 ) (l1=l1l)->
lll[l1l->lll[1-1] =1]=l11l;ll1(l11 =1+1;l11<=l;
++l11){l1=ll11; lll1 = (ll1l=( ll11=l1l))->
lll; lllll =( l1l=l1)->lll; ll=(l1ll=1-1
);ll1(;ll1l-> lll1l||l11l!= *lll1;){l1ll
+=l11**lll1++ ;l1ll1 ll111 (++ll>llll){
l1lll lll1=( ll1l =ll1l-> lll1l)->lll;
}}ll1(;l1ll; ){l1ll1 ll111 (++ll>=llll)
{ l1lll} } * lllll=l11l;}
ll1(l=(ll=1- 1);(l<llll)&&
(l1->lll[ l] !=l11l);++l); ll1 (;l1;l1=
l1->ll1l1,l= llll){ll1(--l ;l>=1-1;--l,
++ll)printf( (ll)?((ll%19) ?"%04d":(ll=
19,"\n%04d") ):"%4d",l1-> lll[l] ) ; }
ll1ll(10); }
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
===Iterative===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 978 ⟶ 2,594:
static int Factorial(int number)
{
intif(number accumulator< =0) 1;
throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
for (int factor = 1; factor <= number; factor++)
 
var accumulator = 1;
for (var factor = 1; factor <= number; factor++)
{
accumulator *= factor;
Line 990 ⟶ 2,609:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 998 ⟶ 2,617:
static int Factorial(int number)
{
if(number < 0)
throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
 
return number == 0 ? 1 : number * Factorial(number - 1);
}
Line 1,005 ⟶ 2,627:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 1,013 ⟶ 2,635:
static int Factorial(int number)
{
if(number < 0)
throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
 
return Factorial(number, 1);
}
Line 1,018 ⟶ 2,643:
static int Factorial(int number, int accumulator)
{
if(number < 0)
throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
if(accumulator < 1)
throw new ArgumentOutOfRangeException(nameof(accumulator), accumulator, "Must be a positive number.");
 
return number == 0 ? accumulator : Factorial(number - 1, number * accumulator);
}
Line 1,025 ⟶ 2,655:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Functional===
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,041 ⟶ 2,671:
Console.WriteLine(Factorial(10));
}
}</langsyntaxhighlight>
===Arbitrary Precision===
{{libheader|System.Numerics}}
<code>Factorial()</code> can calculate 200000! in around 40 seconds over at Tio.run.<br>
<code>FactorialQ()</code> can calculate 1000000! in around 40 seconds over at Tio.run.<br><br>
 
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;
class Program
{
static BigInteger factorial(int n) // iterative
{
BigInteger acc = 1; for (int i = 1; i <= n; i++) acc *= i; return acc;
}
 
static public BigInteger Factorial(int number) // functional
{
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];
}
 
static void Main(string[] args)
{
Console.WriteLine(Factorial(250));
}
}</syntaxhighlight>
{{out}}
<pre>3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000</pre>
 
=={{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,052 ⟶ 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 do-while loop.
<syntaxhighlight lang="cpp">//iteration with while
<lang cpp>long long int Factorial(long long int m_nValue)
long long int factorial(long long int n)
{
{
long long int result=m_nValue;
long long int result_nextr = 1;
while(1<n)
long long int pc = m_nValue;
dor *= n--;
return {r;
}</syntaxhighlight>
result_next = result*(pc-1);
result = result_next;
pc--;
}while(pc>2);
m_nValue = result;
return m_nValue;
}</lang>
 
===Template===
<langsyntaxhighlight lang="cpp">template <int N>
struct Factorial
{
Line 1,090 ⟶ 2,763:
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}</langsyntaxhighlight>
 
===Compare all Solutions (except the meta)===
<syntaxhighlight lang="cpp">#include <algorithm>
#include <chrono>
#include <iostream>
#include <numeric>
#include <vector>
#include <boost/iterator/counting_iterator.hpp>
 
using ulli = unsigned long long int;
 
// bad style do-while and wrong for Factorial1(0LL) -> 0 !!!
ulli Factorial1(ulli m_nValue) {
ulli result = m_nValue;
ulli result_next;
ulli pc = m_nValue;
do {
result_next = result * (pc - 1);
result = result_next;
pc--;
} while (pc > 2);
return result;
}
 
// iteration with while
ulli Factorial2(ulli n) {
ulli r = 1;
while (1 < n)
r *= n--;
return r;
}
 
// recursive
ulli Factorial3(ulli n) {
return n < 2 ? 1 : n * Factorial3(n - 1);
}
 
// tail recursive
inline ulli _fac_aux(ulli n, ulli acc) {
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
ulli Factorial4(ulli n) {
return _fac_aux(n, 1);
}
 
// accumulate with functor
ulli Factorial5(ulli n) {
// last is one-past-end
return std::accumulate(boost::counting_iterator<ulli>(1ULL),
boost::counting_iterator<ulli>(n + 1ULL), 1ULL,
std::multiplies<ulli>());
}
 
// accumulate with lambda
ulli Factorial6(ulli n) {
// last is one-past-end
return std::accumulate(boost::counting_iterator<ulli>(1ULL),
boost::counting_iterator<ulli>(n + 1ULL), 1ULL,
[](ulli a, ulli b) { return a * b; });
}
 
int main() {
ulli v = 20; // max value with unsigned long long int
ulli result;
std::cout << std::fixed;
using duration = std::chrono::duration<double, std::micro>;
 
{
auto t1 = std::chrono::high_resolution_clock::now();
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";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
result = Factorial2(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "while(2) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
result = Factorial3(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "recursive(3) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
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";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
result = Factorial5(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "std::accumulate(5) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
}
 
{
auto t1 = std::chrono::high_resolution_clock::now();
result = Factorial6(v);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "std::accumulate lambda(6) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
}
}</syntaxhighlight>
<pre>do-while(1) result 2432902008176640000 took 0.110000 µs
while(2) result 2432902008176640000 took 0.078000 µs
recursive(3) result 2432902008176640000 took 0.057000 µs
tail recursive(4) result 2432902008176640000 took 0.056000 µs
std::accumulate(5) result 2432902008176640000 took 0.056000 µs
std::accumulate lambda(6) result 2432902008176640000 took 0.079000 µs
</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,118 ⟶ 2,943:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">proc fac(n) {
var r = 1;
for i in 1..n do
Line 1,127 ⟶ 2,952:
return r;
}</langsyntaxhighlight>
 
=={{header|Chef}}==
<langsyntaxhighlight Cheflang="chef">Caramel Factorials.
 
Only reads one value.
Line 1,146 ⟶ 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,161 ⟶ 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,174 ⟶ 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,191 ⟶ 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,213 ⟶ 3,052:
println(factorialStatic(static 5)); // 120
println(factorial(Int64(20))); // 2432902008176640000
}</langsyntaxhighlight>
 
=={{header|Clio}}==
 
=== Recursive ===
<syntaxhighlight lang="clio">
fn factorial n:
if n <= 1: n
else:
n * (n - 1 -> factorial)
 
10 -> factorial -> print
</syntaxhighlight>
 
=={{header|CLIPS}}==
<langsyntaxhighlight lang="lisp"> (deffunction factorial (?a)
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
Line 1,223 ⟶ 3,074:
1
else
(* ?a (factorial (- ?a 1))))))</langsyntaxhighlight>
 
=={{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,255 ⟶ 3,143:
 
factorial(f 12)
message("12! = ${f}")</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 1,262 ⟶ 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,304 ⟶ 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,314 ⟶ 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,333 ⟶ 3,273:
ENDIF
RETURN r
ENDPROC Recursive</langsyntaxhighlight>
 
=={{header|Comefrom0x10}}==
 
This is iterative; recursion is not possible in Comefrom0x10.
 
<syntaxhighlight lang="cf0x10">n = 5 # calculates n!
acc = 1
 
factorial
comefrom
 
comefrom accumulate if n < 1
 
accumulate
comefrom factorial
acc = acc * n
comefrom factorial if n is 0
n = n - 1
 
acc # prints the result</syntaxhighlight>
 
=={{header|Common Lisp}}==
Recursive:
<langsyntaxhighlight lang="lisp">(defun factfactorial (n)
(if (zerop n) 1 (* n (factorial (1- n)))))</syntaxhighlight>
(if (< n 2)
 
1
or
(* n (fact(- n 1)))))</lang>
 
<syntaxhighlight lang="lisp">(defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))))</syntaxhighlight>
 
Tail Recursive:
<syntaxhighlight lang="lisp">(defun factorial (n &optional (m 1))
(if (zerop n) m (factorial (1- n) (* m n))))</syntaxhighlight>
 
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===
{{Works with|Allegro CL|10.1}}
 
<syntaxhighlight lang="lisp">;; Project : Factorial
 
(defun factorial (n)
(cond ((= n 1) 1)
(t (* n (factorial (- n 1))))))
(format t "~a" "factorial of 8: ")
(factorial 8)</syntaxhighlight>
Output:
<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 1,398 ⟶ 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 1,416 ⟶ 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===
<syntaxhighlight lang="crystal">def factorial(x : Int)
ans = 1
(1..x).each do |i|
ans *= i
end
return ans
end</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="crystal">def factorial(x : Int)
if x <= 1
return 1
end
return x * factorial(x - 1)
end</syntaxhighlight>
 
=={{header|D}}==
===Iterative Version===
<langsyntaxhighlight lang="d">uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
Line 1,438 ⟶ 3,445:
// Computed and printed at run-time.
12.factorial.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>479001600u
Line 1,444 ⟶ 3,451:
 
===Recursive Version===
<langsyntaxhighlight lang="d">uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
Line 1,462 ⟶ 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 1,481 ⟶ 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 1,506 ⟶ 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 1,521 ⟶ 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 1,537 ⟶ 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 1,559 ⟶ 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 1,593 ⟶ 3,585:
begin
Writeln('5! = ', FactorialIterative(5));
end.</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Delphilang="delphi">program Factorial2;
 
{$APPTYPE CONSOLE}
Line 1,610 ⟶ 3,602:
begin
Writeln('5! = ', FactorialRecursive(5));
end.</langsyntaxhighlight>
 
===Tail Recursive===
<langsyntaxhighlight Delphilang="delphi">program Factorial3;
 
{$APPTYPE CONSOLE}
Line 1,636 ⟶ 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()
for(i=1,i<=n,++i)
{
factorial = factorial * i
}
showln "factorial of " + n + " is " + factorial
</syntaxhighlight>
 
=={{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 1,648 ⟶ 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}}==
 
<syntaxhighlight lang="dyalect">func factorial(n) {
if n < 2 {
1
} else {
n * factorial(n - 1)
}
}</syntaxhighlight>
 
=={{header|Dylan}}==
 
<lang dylan>define method factorial(n)
=== Functional ===
reduce1(\*, range(from: 1, to: n));
 
end</lang>
<syntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
error("invalid argument");
else
reduce1(\*, range(from: 1, to: n))
end
end method;
</syntaxhighlight>
 
=== Iterative ===
 
<syntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
error("invalid argument");
else
let total = 1;
for (i from n to 2 by -1)
total := total * i;
end;
total
end
end method;
</syntaxhighlight>
 
=== Recursive ===
 
<syntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
error("invalid argument");
end;
local method loop (n)
if (n <= 2)
n
else
n * loop(n - 1)
end
end;
loop(n)
end method;
</syntaxhighlight>
 
=== Tail recursive ===
 
<syntaxhighlight lang="dylan">
define method factorial (n)
if (n < 1)
error("invalid argument");
end;
// Dylan implementations are required to perform tail call optimization so
// this is equivalent to iteration.
local method loop (n, total)
if (n <= 2)
total
else
let next = n - 1;
loop(next, total * next)
end
end;
loop(n, n)
end method;
</syntaxhighlight>
 
=={{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">
func factorial n .
r = 1
for i = 2 to n
r *= i
.
return r
.
print factorial 7
</syntaxhighlight>
 
=={{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 1,684 ⟶ 3,824:
(fact 10)
→ 3628800
</syntaxhighlight>
</lang>
===Tail recursive===
<langsyntaxhighlight lang="scheme">
(define (fact n (acc 1))
(if (zero? n) acc
Line 1,692 ⟶ 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 1,720 ⟶ 3,983:
return (ans);
end
</syntaxhighlight>
</lang>
===Recursive===
<syntaxhighlight lang="egl">
<lang EGL>
function fact(n int in) returns (bigint)
if (n < 0)
Line 1,734 ⟶ 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 1,788 ⟶ 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 1,808 ⟶ 4,071:
def fac_tail(1, acc), do: acc
def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n)
 
# Tail recursive function with default parameter
def fac_default(n, acc \\ 1)
def fac_default(0, acc), do: acc
def fac_default(n, acc) when n > 0, do: fac_default(n - 1, acc * n)
# Using Enumeration features
def fac_reduce(0), do: 1
def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2)
 
end</lang>
# Using Enumeration features with pipe operator
def fac_pipe(0), do: 1
def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)
 
end</syntaxhighlight>
 
=={{header|Elm}}==
 
===Recursive===
<lang elm>factorial : Int -> Int
 
<syntaxhighlight lang="elm">
factorial : Int -> Int
factorial n =
if n < 1 then 1 else n*factorial(n-1)</lang>
</syntaxhighlight>
 
===Tail Recursive===
 
<syntaxhighlight lang="elm">
factorialAux : Int -> Int -> Int
factorialAux a acc =
if a < 2 then acc else factorialAux (a - 1) (a * acc)
 
factorial : Int -> Int
factorial a =
factorialAux a 1
</syntaxhighlight>
 
===Functional===
 
<syntaxhighlight lang="elm">
import List exposing (product, range)
 
factorial : Int -> Int
factorial a =
product (range 1 a)
</syntaxhighlight>
 
=={{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 1,854 ⟶ 4,222:
 
'''Iterative procedure:'''
<syntaxhighlight lang="erre">
<lang ERRE>
PROCEDURE FACTORIAL(X%->F)
F=1
Line 1,863 ⟶ 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 1,877 ⟶ 4,245:
Straight forward methods
===Iterative===
<langsyntaxhighlight Euphorialang="euphoria">function factorial(integer n)
atom f = 1
while n > 1 do
Line 1,885 ⟶ 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 1,894 ⟶ 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 1,904 ⟶ 4,272:
return factorial(n-1, n*acc)
end if
end function</langsyntaxhighlight>
 
==='Paper tape' / Virtual Machine version===
Line 1,910 ⟶ 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,015 ⟶ 4,383:
end if
ip += 1
end while</langsyntaxhighlight>
 
=={{header|Excel}}==
 
Choose a cell and write in the function bar on the top :
 
<syntaxhighlight lang="excel">
=fact(5)
</syntaxhighlight>
 
The result is shown as :
 
<pre>
120
</pre>
 
=={{header|Ezhil}}==
Recursive
<langsyntaxhighlight lang="src="Pythonpython"">
நிரல்பாகம் fact ( n )
@( n == 0 ) ஆனால்
Line 2,029 ⟶ 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,047 ⟶ 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,069 ⟶ 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,108 ⟶ 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,129 ⟶ 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>
===FORTRAN 77===
<lang fortran> FUNCTION FACT(N)
INTEGER N,I,FACT
FACT=1
DO 10 I=1,N
10 FACT=FACT*I
END</lang>
 
Recursive functions were added in Fortran 90, allowing the following:
=={{header|FPr}}==
<syntaxhighlight lang="fortran">INTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS)
FP-Way
INTEGER, INTENT(IN) :: X
<lang fpr>fact==((1&),iota)\(1*2)& </lang>
Recursive
<lang fpr>fact==(id<=1&)->(1&);id*fact°id-1& </lang>
 
IF (X <= 1) THEN
=={{header|FreeBASIC}}==
ANS = 1
<lang freebasic>' FB 1.05.0 Win64
ELSE
ANS = X * RECURSIVE_FACTORIAL(X-1)
END IF
 
END FUNCTION RECURSIVE_FACTORIAL</syntaxhighlight>
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
 
===FORTRAN 77===
Function Factorial_Recursive(n As Integer) As Integer
<syntaxhighlight lang="fortran"> INTEGER FUNCTION MFACT(N)
If n = 0 Then Return 1
INTEGER N,I,FACT
Return n * Factorial_Recursive(n - 1)
FACT=1
End Function
IF (N.EQ.0) GOTO 20
 
For i As Integer = 1 ToDO 510 I=1,N
FACT=FACT*I
Print i; " =>"; Factorial_Iterative(i)
10 CONTINUE
Next
20 CONTINUE
 
For i As Integer = 6 ToMFACT = 10FACT
Print Using "##"; i; RETURN
END</syntaxhighlight>
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 2,196 ⟶ 4,608:
 
===Iterative===
<langsyntaxhighlight lang="fishshell">
function factorial
set x $argv[1]
Line 2,205 ⟶ 4,617:
echo $result
end
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="fishshell">
function factorial
set x $argv[1]
Line 2,217 ⟶ 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 2,240 ⟶ 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 2,257 ⟶ 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}}==
{{incorrect|Futhark|Futhark's syntax has changed, so this example will not compile}}
 
=== 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 2,360 ⟶ 4,801:
Recursive: 12 = 479001600
</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 2,399 ⟶ 4,841:
set xrange [0:4.95]
set key left
plot factorial(x)</langsyntaxhighlight>
 
=={{header|Go}}==
===Iterative===
Iterative, sequential, but at least handling big numbers:
Sequential, but at least handling big numbers:
<lang go>package main
<syntaxhighlight lang="go">package main
 
import (
Line 2,424 ⟶ 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 2,440 ⟶ 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===
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
)
 
func factorial(n float64) float64 {
return math.Gamma(n + 1)
}
 
func main() {
for i := 0.; i <= 10; i++ {
fmt.Println(i, factorial(i))
}
fmt.Println(100, factorial(100))
}</syntaxhighlight>
{{out}}
<pre>
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3.6288e+06
100 9.332621544394405e+157
</pre>
===Built in, Lgamma===
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
"math/big"
)
 
func lfactorial(n float64) float64 {
l, _ := math.Lgamma(n + 1)
return l
}
 
func factorial(n float64) *big.Float {
i, frac := math.Modf(lfactorial(n) * math.Log2E)
z := big.NewFloat(math.Exp2(frac))
return z.SetMantExp(z, int(i))
}
 
func main() {
for i := 0.; i <= 10; i++ {
fmt.Println(i, factorial(i))
}
fmt.Println(100, factorial(100))
fmt.Println(800, factorial(800))
}</syntaxhighlight>
{{out}}
<pre>
0 1
1 1
2 2
3 6
4 24
5 119.99999999999994
6 720.0000000000005
7 5039.99999999999
8 40320.000000000015
9 362880.0000000001
10 3.6288000000000084e+06
100 9.332621544394454e+157
800 7.710530113351238e+1976
</pre>
 
=={{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 2,469 ⟶ 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 2,496 ⟶ 5,018:
factList.each { printf ' %3d', it }
println()
}</langsyntaxhighlight>
 
{{out}}
Line 2,503 ⟶ 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===
<syntaxhighlight lang="haxe">static function factorial(n:Int):Int {
var result = 1;
while (1<n)
result *= n--;
return result;
}</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="haxe">static function factorial(n:Int):Int {
return n == 0 ? 1 : n * factorial2(n - 1);
}</syntaxhighlight>
 
===Tail-Recursive===
<syntaxhighlight lang="haxe">inline static function _fac_aux(n, acc:Int):Int {
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
 
static function factorial(n:Int):Int {
return _fac_aux(n,1);
}</syntaxhighlight>
 
===Functional===
<syntaxhighlight lang="haxe">static function factorial(n:Int):Int {
return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);
}</syntaxhighlight>
 
===Comparison===
<syntaxhighlight lang="haxe">using StringTools;
using Lambda;
 
class Factorial {
// iterative
static function factorial1(n:Int):Int {
var result = 1;
while (1<n)
result *= n--;
return result;
}
 
// recursive
static function factorial2(n:Int):Int {
return n == 0 ? 1 : n * factorial2(n - 1);
}
 
// tail-recursive
inline static function _fac_aux(n, acc:Int):Int {
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
 
static function factorial3(n:Int):Int {
return _fac_aux(n,1);
}
 
// functional
static function factorial4(n:Int):Int {
return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);
}
 
static function main() {
var v = 12;
// iterative
var start = haxe.Timer.stamp();
var result = factorial1(v);
var duration = haxe.Timer.stamp() - start;
Sys.println('iterative'.rpad(' ', 20) + 'result: $result time: $duration ms');
 
// recursive
start = haxe.Timer.stamp();
result = factorial2(v);
duration = haxe.Timer.stamp() - start;
Sys.println('recursive'.rpad(' ', 20) + 'result: $result time: $duration ms');
 
// tail-recursive
start = haxe.Timer.stamp();
result = factorial3(v);
duration = haxe.Timer.stamp() - start;
Sys.println('tail-recursive'.rpad(' ', 20) + 'result: $result time: $duration ms');
 
// functional
start = haxe.Timer.stamp();
result = factorial4(v);
duration = haxe.Timer.stamp() - start;
Sys.println('functional'.rpad(' ', 20) + 'result: $result time: $duration ms');
}
}</syntaxhighlight>
 
{{out}}
<pre>
iterative result: 479001600 time: 6.198883056640625e-06 ms
recursive result: 479001600 time: 1.31130218505859375e-05 ms
tail-recursive result: 479001600 time: 1.9073486328125e-06 ms
functional result: 479001600 time: 1.40666961669921875e-05 ms
</pre>
 
=={{header|hexiscript}}==
===Iterative===
<syntaxhighlight lang="hexiscript">fun fac n
let acc 1
while n > 0
let acc (acc * n--)
endwhile
return acc
endfun</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="hexiscript">fun fac n
if n <= 0
return 1
else
return n * fac (n - 1)
endif
endfun</syntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">WRITE(Clipboard) factorial(6) ! pasted: 720
 
FUNCTION factorial(n)
Line 2,546 ⟶ 5,220:
factorial = factorial * i
ENDDO
END</langsyntaxhighlight>
 
=={{header|IHolyC}}==
=== Iterative ===
<lang i>
<syntaxhighlight lang="holyc">U64 Factorial(U64 n) {
function fact(n, acc) r {
U64 i, result = 1;
if n = 0
for (i = 1; i <= n; ++i)
return acc
result *= i;
end
return result;
return fact(n-1, n*acc)
}
 
Print("1: %d\n", Factorial(1));
function factorial(n) r {
Print("10: %d\n", Factorial(10));</syntaxhighlight>
return fact(n, 1)
 
Note: Does not support negative numbers.
 
=== Recursive ===
<syntaxhighlight lang="holyc">I64 Factorial(I64 n) {
if (n == 0)
return 1;
if (n < 0)
return -1 * ((-1 * n) * Factorial((-1 * n) - 1));
return n * Factorial(n - 1));
}
 
Print("+1: %d\n", Factorial(1));
Print("+10: %d\n", Factorial(10));
Print("-10: %d\n", Factorial(-10));</syntaxhighlight>
 
=={{header|Hy}}==
<syntaxhighlight lang="clojure">(defn ! [n]
(reduce *
(range 1 (inc n))
1))
 
(print (! 6)) ; 720
(print (! 0)) ; 1</syntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">concept factorial(n) {
return n!
}
software {
print(factorial(-23))
print(factorial(0))
print(factorial(1))
Line 2,567 ⟶ 5,270:
print(factorial(3))
print(factorial(22))
}
}</lang>
</syntaxhighlight>
 
=={{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 2,585 ⟶ 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}}==
FacorialsFactorials 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===
<syntaxhighlight lang="java5">
<lang java5>public static long fact(final int n) {
package programas;
if (n < 0) {
 
System.err.println("No negative numbers");
import java.math.BigInteger;
return 0;
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class IterativeFactorial {
 
public BigInteger factorial(BigInteger n) {
if ( n == null ) {
throw new IllegalArgumentException();
}
longelse ansif ( n.signum() == - 1; ) {
// negative
for (int i = 1; i <= n; i++) {
throw new IllegalArgumentException("Argument must be a non-negative integer");
ans *= i;
}
returnelse ans;{
BigInteger factorial = BigInteger.ONE;
}</lang>
for ( BigInteger i = BigInteger.ONE; i.compareTo(n) < 1; i = i.add(BigInteger.ONE) ) {
factorial = factorial.multiply(i);
}
return factorial;
}
}
 
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger number, result;
boolean error = false;
System.out.println("FACTORIAL OF A NUMBER");
do {
System.out.println("Enter a number:");
try {
number = scanner.nextBigInteger();
result = new IterativeFactorial().factorial(number);
error = false;
System.out.println("Factorial of " + number + ": " + result);
}
catch ( InputMismatchException e ) {
error = true;
scanner.nextLine();
}
 
catch ( IllegalArgumentException e ) {
error = true;
scanner.nextLine();
}
}
while ( error );
scanner.close();
}
 
}
 
</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="java5">
<lang java5>public static long fact(final int n) {
package programas;
if (n < 0){
 
System.err.println("No negative numbers");
import java.math.BigInteger;
return 0;
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class RecursiveFactorial {
 
public BigInteger factorial(BigInteger n) {
if ( n == null ) {
throw new IllegalArgumentException();
}
 
return (n < 2) ? 1 : n * fact(n - 1);
else if ( n.equals(BigInteger.ZERO) ) {
}</lang>
return BigInteger.ONE;
}
else if ( n.signum() == - 1 ) {
// negative
throw new IllegalArgumentException("Argument must be a non-negative integer");
}
else {
return n.equals(BigInteger.ONE)
? BigInteger.ONE
: factorial(n.subtract(BigInteger.ONE)).multiply(n);
}
}
 
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger number, result;
boolean error = false;
System.out.println("FACTORIAL OF A NUMBER");
do {
System.out.println("Enter a number:");
try {
number = scanner.nextBigInteger();
result = new RecursiveFactorial().factorial(number);
error = false;
System.out.println("Factorial of " + number + ": " + result);
}
catch ( InputMismatchException e ) {
error = true;
scanner.nextLine();
}
 
catch ( IllegalArgumentException e ) {
error = true;
scanner.nextLine();
}
}
while ( error );
scanner.close();
 
}
 
}
 
</syntaxhighlight>
 
===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 2,650 ⟶ 5,580:
===Iterative===
 
<langsyntaxhighlight lang="javascript">function factorial(n) {
//check our edge case
if (n < 0) { throw "Number must be non-negative"; }
 
var sumresult = 1;
//we skip zero and one since both are 1 and are identity
while (n > 1) {
sumresult *= n;
n -= 1-;
}
return sumresult;
}</langsyntaxhighlight>
 
===Recursive===
Line 2,667 ⟶ 5,597:
====ES5 (memoized )====
 
<langsyntaxhighlight JavaScriptlang="javascript">(function(x) {
 
var memo = {};
Line 2,677 ⟶ 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 2,711 ⟶ 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
 
<syntaxhighlight lang="javascript">(() => {
<lang JavaScript>(function (n) {
'use strict';
 
// factorial :: Int -> Int
letconst factorial = (n) => range(1, n).reduce(product, 1);
enumFromTo(1, n)
.reduce(product, 1);
 
 
//const producttest ::= Num() -=> Num -> Num
let product = factorial(a, b18) => a * b,;
// --> 6402373705728000
 
// range :: Int -> Int -> [Int]
range = (m, n) =>
Array.from({
length: (n - m) + 1
}, (_, i) => m + i)
 
// GENERIC FUNCTIONS ----------------------------------
 
// product :: Num -> Num -> Num
return factorial(n);
const product = (a, b) => a * b;
 
// range :: Int -> Int -> [Int]
})(18);</lang>
const enumFromTo = (m, n) =>
Array.from({
length: (n - m) + 1
}, (_, i) => m + i);
 
// MAIN ------
return test();
})();</syntaxhighlight>
{{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 2,756 ⟶ 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 2,775 ⟶ 5,769:
end;
# Extract the accumulated value from the output of _fact:
[1, .] | _fact | .[0] ;</langsyntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Factorial, in Jsish */
 
/* recursive */
function fact(n) { return ((n < 2) ? 1 : n * fact(n - 1)); }
 
/* iterative */
function factorial(n:number) {
if (n < 0) throw format("factorial undefined for negative values: %d", n);
 
var fac = 1;
while (n > 1) fac *= n--;
return fac;
}
 
if (Interp.conf('unitTest') > 0) {
;fact(18);
;fact(1);
 
;factorial(18);
;factorial(42);
try { factorial(-1); } catch (err) { puts(err); }
}</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish --U factorial.jsi
fact(18) ==> 6402373705728000
fact(1) ==> 1
factorial(18) ==> 6402373705728000
factorial(42) ==> 1.40500611775288e+51
factorial undefined for negative values: -1</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
The factorial is provided by the standard library.
<lang julia>julia> help(factorial)
Loading help data...
Base.factorial(n)
 
'''Built-in version''':
Factorial of n
<pre>help?> factorial
search: factorial Factorization factorize
 
Base. factorial(n, k)
 
Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at
Compute "factorial(n)/factorial(k)"</lang>
least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n))
Here is its definition from the combinatorics.jl module of the Julia standard library
to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is
<lang julia>
equivalent to gamma(n+1).
function factorial(n::Integer)
 
if n < 0
julia> factorial(6)
return zero(n)
end720
 
julia> factorial(21)
ERROR: OverflowError()
[...]
 
julia> factorial(21.0)
5.109094217170944e19
 
julia> factorial(big(21))
51090942171709440000</pre>
 
'''Dynamic version''':
<syntaxhighlight lang="julia">function fact(n::Integer)
n < 0 && return zero(n)
f = one(n)
for i =in 2:n
f *= i
end
return f
end</lang>
{{out}}
<pre>julia> for i = 10:20
println(factorial(big(i)))
end
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000</pre>
 
for i in 10:20
Another way of writing the factorial function, with arithmetic performed in the precision of the argument.
println("$i -> ", fact(i))
end</syntaxhighlight>
 
{{out}}
<lang julia>fact(n) = prod(one(n):n)</lang>
<pre>10 -> 3628800
11 -> 39916800
12 -> 479001600
13 -> 6227020800
14 -> 87178291200
15 -> 1307674368000
16 -> 20922789888000
17 -> 355687428096000
18 -> 6402373705728000
19 -> 121645100408832000
20 -> 2432902008176640000</pre>
 
'''Alternative version''':
<syntaxhighlight lang="julia">fact2(n::Integer) = prod(Base.OneTo(n))
@show fact2(20)</syntaxhighlight>
{{out}}
<pre>fact2(20) = 2432902008176640000</pre>
 
=={{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 2,850 ⟶ 5,937:
}
return ret;
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun facti(n: Int) = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
var ans = 1L
for (i in 2..n) ans *= i
Line 2,865 ⟶ 5,952:
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
n < 2 -> 1L
else -> n * factr(n - 1)
}
 
Line 2,872 ⟶ 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 ===
<syntaxhighlight lang="langur">val .factorial = fn(.n) fold(fn{*}, 2 .. .n)
writeln .factorial(7)</syntaxhighlight>
 
=== Recursive ===
<syntaxhighlight lang="langur">val .factorial = fn(.x) { if(.x < 2: 1; .x * self(.x - 1)) }
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative ===
<syntaxhighlight lang="langur">val .factorial = fn(.i) {
var .answer = 1
for .x in 2 .. .i {
.answer *= .x
}
.answer
}
 
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative Folding ===
<syntaxhighlight lang="langur">val .factorial = fn(.n) { for[=1] .x in .n { _for *= .x } }
writeln .factorial(7)</syntaxhighlight>
 
{{out}}
<pre>5040</pre>
 
=={{header|Lasso}}==
===Iterative===
<langsyntaxhighlight lang="lasso">define factorial(n) => {
local(x = 1)
with i in generateSeries(2, #n)
Line 2,900 ⟶ 6,075:
}
return #x
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="lasso">define factorial(n) => #n < 2 ? 1 | #n * factorial(#n - 1)</langsyntaxhighlight>
 
=={{header|Latitude}}==
 
===Functional===
<syntaxhighlight lang="latitude">factorial := {
1 upto ($1 + 1) product.
}.</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="latitude">factorial := {
takes '[n].
if { n == 0. } then {
1.
} else {
n * factorial (n - 1).
}.
}.</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="latitude">factorial := {
local 'acc = 1.
1 upto ($1 + 1) do {
acc = acc * $1.
}.
acc.
}.</syntaxhighlight>
 
=={{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 2,912 ⟶ 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 2,945 ⟶ 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 2,961 ⟶ 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 2,981 ⟶ 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 3,030 ⟶ 6,238:
end repeat
return res
end</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">- factorial x : INTEGER : INTEGER <- (
+ result : INTEGER;
(x <= 1).if {
Line 3,041 ⟶ 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 3,068 ⟶ 6,319:
// iterative
function factorialit n
put 1 into f
if n > 1 then
repeat with i = 1 to n
Line 3,075 ⟶ 6,326:
end if
return f
end factorialit</langsyntaxhighlight>
 
=={{header|LLVM}}==
<syntaxhighlight lang="llvm">; ModuleID = 'factorial.c'
; source_filename = "factorial.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"
 
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
 
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
 
$"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = comdat any
 
@"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1
 
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
 
; Function Attrs: noinline nounwind optnone uwtable
define i32 @factorial(i32) #0 {
;-- local copy of n
%2 = alloca i32, align 4
;-- long result
%3 = alloca i32, align 4
;-- int i
%4 = alloca i32, align 4
;-- local n = parameter n
store i32 %0, i32* %2, align 4
;-- result = 1
store i32 1, i32* %3, align 4
;-- i = 1
store i32 1, i32* %4, align 4
br label %loop
 
loop:
;-- i <= n
%5 = load i32, i32* %4, align 4
%6 = load i32, i32* %2, align 4
%7 = icmp sle i32 %5, %6
br i1 %7, label %loop_body, label %exit
 
loop_body:
;-- result *= i
%8 = load i32, i32* %4, align 4
%9 = load i32, i32* %3, align 4
%10 = mul nsw i32 %9, %8
store i32 %10, i32* %3, align 4
br label %loop_increment
 
loop_increment:
;-- ++i
%11 = load i32, i32* %4, align 4
%12 = add nsw i32 %11, 1
store i32 %12, i32* %4, align 4
br label %loop
 
exit:
;-- return result
%13 = load i32, i32* %3, align 4
ret i32 %13
}
 
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
;-- factorial(5)
%1 = call i32 @factorial(i32 5)
;-- printf("%ld\n", factorial(5))
%2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@", i32 0, i32 0), i32 %1)
;-- return 0
ret i32 0
}
 
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
 
!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}
 
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</syntaxhighlight>
{{out}}
<pre>120</pre>
 
=={{header|Logo}}==
===Recursive===
 
<langsyntaxhighlight lang="logo">to factorial :n
if :n < 2 [output 1]
output :n * factorial :n-1
end</langsyntaxhighlight>
 
===Iterative===
Line 3,089 ⟶ 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 3,112 ⟶ 6,447:
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR Loop
KTHXBYE</langsyntaxhighlight>
{{Out}}
<pre>0! = 1
Line 3,130 ⟶ 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 3,140 ⟶ 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 3,146 ⟶ 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 3,152 ⟶ 6,487:
return t[n]
end
})</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
M2000 Interpreter running in M2000 Environment, a Visual Basic 6.0 application. So we use Decimals, for output.
 
Normal Print overwrite console screen, and at the last line scroll up on line, feeding a new clear line. Some time needed to print over and we wish to erase the line before doing that. Here we use another aspect of this variant of Print. Any special formatting function $() are kept local, so after the end of statement formatting return to whatever has before.
 
We want here to change width of column. Normally column width for all columns are the same. For this statement (Print Over) this not hold, we can change column width as print with it. Also we can change justification, and we can choose on column the use of proportional or non proportional text rendering (console use any font as non proportional by default, and if it is proportional font then we can use it as proportional too). Because no new line append to end of this statement, we need to use a normal Print to send new line.
1@ is 1 in Decimal type (27 digits).
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Locale 1033 ' ensure #,### print with comma
Function factorial (n){
If n<0 then Error "Factorial Error!"
If n>27 then Error "Overflow"
m=1@:While n>1 {m*=n:n--}:=m
}
Const Proportional=4
Const ProportionalLeftJustification=5
Const NonProportional=0
Const NonProportionalLeftJustification=1
For i=1 to 27
\\ we can print over (erasing line first), without new line at the end
\\ and we can change how numbers apears, and the with of columns
\\ numbers by default have right justification
\\ all $() format have temporary use in this kind of print.
Print Over $(Proportional),$("\f\a\c\t\o\r\i\a\l\(#\)\=",15), i, $(ProportionalLeftJustification), $("#,###",40), factorial(i)
Print \\ new line
Next i
}
Checkit
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
factorial(1)= 1
factorial(2)= 2
factorial(3)= 6
factorial(4)= 24
factorial(5)= 120
factorial(6)= 720
factorial(7)= 5,040
factorial(8)= 40,320
factorial(9)= 362,880
factorial(10)= 3,628,800
factorial(11)= 39,916,800
factorial(12)= 479,001,600
factorial(13)= 6,227,020,800
factorial(14)= 87,178,291,200
factorial(15)= 1,307,674,368,000
factorial(16)= 20,922,789,888,000
factorial(17)= 355,687,428,096,000
factorial(18)= 6,402,373,705,728,000
factorial(19)= 121,645,100,408,832,000
factorial(20)= 2,432,902,008,176,640,000
factorial(21)= 51,090,942,171,709,440,000
factorial(22)= 1,124,000,727,777,607,680,000
factorial(23)= 25,852,016,738,884,976,640,000
factorial(24)= 620,448,401,733,239,439,360,000
factorial(25)= 15,511,210,043,330,985,984,000,000
factorial(26)= 403,291,461,126,605,635,584,000,000
factorial(27)= 10,888,869,450,418,352,160,768,000,000
</pre >
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`factorial',`ifelse(`$1',0,1,`eval($1*factorial(decr($1)))')')dnl
dnl
factorial(5)</langsyntaxhighlight>
 
{{out}}
Line 3,163 ⟶ 6,562:
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>
 
=={{header|MANOOL}}==
 
Recursive version, MANOOLish &ldquo;cascading&rdquo; notation:
<syntaxhighlight lang="manool">
{ let rec
{ Fact = -- compile-time constant binding
{ proc { N } as -- precondition: N.IsI48[] & (N >= 0)
: if N == 0 then 1 else
N * Fact[N - 1]
}
}
in -- use Fact here or just make the whole expression to evaluate to it:
Fact
}
</syntaxhighlight>
 
Conventional notation (equivalent to the above up to AST):
<syntaxhighlight lang="manool">
{ let rec
{ Fact = -- compile-time constant binding
{ proc { N } as -- precondition: N.IsI48[] & (N >= 0)
{ if N == 0 then 1 else
N * Fact[N - 1]
}
}
}
in -- use Fact here or just make the whole expression to evaluate to it:
Fact
}
</syntaxhighlight>
 
Iterative version (in MANOOL, probably more appropriate in this particular case):
<syntaxhighlight lang="manool">
{ let
{ Fact = -- compile-time constant binding
{ proc { N } as -- precondition: N.IsI48[] & (N >= 0)
: var { Res = 1 } in -- variable binding
: do Res after -- return result
: while N <> 0 do -- loop while N does not equal to zero
Res = N * Res; N = N - 1
}
}
in -- use Fact here or just make the whole expression to evaluate to it:
Fact
}
</syntaxhighlight>
 
=={{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 3,178 ⟶ 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 3,221 ⟶ 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 3,247 ⟶ 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 3,268 ⟶ 6,751:
)
fac
)</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="maxscript">fn factorial_rec n =
(
local fac = 1
Line 3,278 ⟶ 6,761:
)
fac
)</langsyntaxhighlight>
 
=={{header|Mercury}}==
=== Recursive (using arbitrary large integers and memoisation) ===
<langsyntaxhighlight Mercurylang="mercury">:- module factorial.
 
:- interface.
Line 3,297 ⟶ 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 3,317 ⟶ 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|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">((dup 0 ==) 'succ (dup pred) '* linrec) :factorial</syntaxhighlight>
 
=={{header|MiniScript}}==
=== Iterative ===
<syntaxhighlight lang="miniscript">factorial = function(n)
result = 1
for i in range(2,n)
result = result * i
end for
return result
end function
 
print factorial(10)</syntaxhighlight>
 
=== Recursive ===
<syntaxhighlight lang="miniscript">factorial = function(n)
if n <= 0 then return 1 else return n * factorial(n-1)
end function
 
print factorial(10)</syntaxhighlight>
{{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 ===
<lang mips>
<syntaxhighlight lang="mips">
##################################
# Factorial; iterative #
Line 3,372 ⟶ 6,895:
li $v0, 10 #set syscall arg to EXIT
syscall #make the syscall
</syntaxhighlight>
</lang>
=== Recursive ===
<syntaxhighlight lang="mips">
#reference code
#int factorialRec(int n){
# if(n<2){return 1;}
# else{ return n*factorial(n-1);}
#}
.data
n: .word 5
result: .word
.text
main:
la $t0, n
lw $a0, 0($t0)
jal factorialRec
la $t0, result
sw $v0, 0($t0)
addi $v0, $0, 10
syscall
factorialRec:
addi $sp, $sp, -8 #calling convention
sw $a0, 0($sp)
sw $ra, 4($sp)
addi $t0, $0, 2 #if (n < 2) do return 1
slt $t0, $a0, $t0 #else return n*factorialRec(n-1)
beqz $t0, anotherCall
lw $ra, 4($sp) #recursive anchor
lw $a0, 0($sp)
addi $sp, $sp, 8
addi $v0, $0, 1
jr $ra
anotherCall:
addi $a0, $a0, -1
jal factorialRec
 
lw $ra, 4($sp)
lw $a0, 0($sp)
addi $sp, $sp, 8
mul $v0, $a0, $v0
jr $ra
</syntaxhighlight>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def factorial_iterative(n:int)
2.upto(n-1) do |i|
n *= i
Line 3,382 ⟶ 6,950:
end
 
puts factorial_iterative 10</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
Line 3,391 ⟶ 6,959:
=={{header|ML/I}}==
===Iterative===
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Factorial - iterative
MCSKIP MT,<>
Line 3,407 ⟶ 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 3,421 ⟶ 6,989:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Factorial;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
 
PROCEDURE Factorial(n : CARDINAL) : CARDINAL;
VAR result : CARDINAL;
BEGIN
result := 1;
WHILE n#0 DO
result := result * n;
DEC(n)
END;
RETURN result
END Factorial;
 
VAR
buf : ARRAY[0..63] OF CHAR;
n : CARDINAL;
BEGIN
FOR n:=0 TO 10 DO
FormatString("%2c! = %7c\n", buf, n, Factorial(n));
WriteString(buf)
END;
 
ReadChar
END Factorial.</syntaxhighlight>
 
=={{header|Modula-3}}==
===Iterative===
<langsyntaxhighlight lang="modula3">PROCEDURE FactIter(n: CARDINAL): CARDINAL =
VAR
result := n;
Line 3,435 ⟶ 7,031:
END;
RETURN result;
END FactIter;</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="modula3">PROCEDURE FactRec(n: CARDINAL): CARDINAL =
VAR result := 1;
 
Line 3,445 ⟶ 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 3,461 ⟶ 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 3,475 ⟶ 7,083:
Write $$factorial(3) ; 6
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative numberrnumber
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 3,485 ⟶ 7,093:
}
return factorial
}</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang="nanoquery">def factorial(n)
result = 1
for i in range(1, n)
result = result * i
end
return result
end</syntaxhighlight>
 
=={{header|Neko}}==
<langsyntaxhighlight lang="neko">var factorial = function(number) {
var i = 1;
var result = 1;
Line 3,500 ⟶ 7,118:
};
 
$print(factorial(10));</langsyntaxhighlight>
 
=={{header|Nemerle}}==
Line 3,506 ⟶ 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 3,540 ⟶ 7,158:
accumulator //implicit return
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 3,593 ⟶ 7,211:
fact = 1
 
return fact</langsyntaxhighlight>
{{out}}
<pre>
Line 3,603 ⟶ 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.
 
<syntaxhighlight lang="c">int fact(int n) { return n!; }</syntaxhighlight>
{{out}}
<pre>prompt$ nickle
> load "fact.5c"
> fact(66)
544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000
> fact(-5)
1
> -5!
-120
> fact(1.1)
Unhandled exception invalid_argument ("Incompatible argument", 0, 1.1)
<stdin>:11: fact ((11/10));</pre>
 
Note the precedence of factorial before negation, (-5)! is 1 in Nickle, -5! is the negation of 5!, -120.
 
Also note how the input of 1.1 is internally managed as 11/10 in the error message.
 
=={{header|Nim}}==
===Library===
<syntaxhighlight lang="nim">
import math
let i:int = fac(x)
</syntaxhighlight>
===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 12..x+1:
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:
<syntaxhighlight lang="nyquist">(defun factorial (n)
(do ((x n (* x n)))
((= n 1) x)
(setq n (1- n))))</syntaxhighlight>
 
Recursive:
<syntaxhighlight lang="nyquist">(defun factorial (n)
(if (= n 1)
1
(* n (factorial (1- n)))))</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="modula2">
<lang oberon2>
MODULE Factorial;
IMPORT
Line 3,677 ⟶ 7,358:
END
END Factorial.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,701 ⟶ 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 3,711 ⟶ 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===
All of the previous examples use normal OCaml ints, so on a 64-bit platform the factorial of 100 will be equal to 0, rather than to a 158-digit number.
 
The following code uses the Zarith package to calculate the factorials of larger numbers:
<syntaxhighlight lang="ocaml">let rec factorial n =
let rec loop acc = function
| 0 -> acc
| n -> loop (Z.mul (Z.of_int n) acc) (n - 1)
in loop Z.one n
 
let () =
if not !Sys.interactive then
begin
Sys.argv.(1) |> int_of_string |> factorial |> Z.print;
print_newline ()
end</syntaxhighlight>
 
{{out}}
<pre>$ ocamlfind ocamlopt -package zarith zarith.cmxa fact.ml -o fact
$ ./fact 100
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</pre>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">% built in factorial
printf("%d\n", factorial(50));
 
Line 3,757 ⟶ 7,530:
endfunction
 
printf("%d\n", iter_fact(50));</langsyntaxhighlight>
 
{{out}}
Line 3,771 ⟶ 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 3,789 ⟶ 7,579:
=={{header|Order}}==
Simple recursion:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fac \
Line 3,797 ⟶ 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 3,809 ⟶ 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 3,826 ⟶ 7,616:
in
{Loop N 1}
end</langsyntaxhighlight>
=== Iterative ===
<langsyntaxhighlight lang="oz">fun {Fac3 N}
Result = {NewCell 1}
in
Line 3,835 ⟶ 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 3,841 ⟶ 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 3,863 ⟶ 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 3,877 ⟶ 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 3,885 ⟶ 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 3,904 ⟶ 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 3,913 ⟶ 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 3,940 ⟶ 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}}
<lang perl>use ntheory qw/factorial/;
<syntaxhighlight 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.
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.
<lang Phix>global function factorial(integer n)
<!--<syntaxhighlight lang="phix">-->
atom res = 1
<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>
while n>1 do
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
res *= n
<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>
n -= 1
<span style="color: #000000;">res</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">n</span>
end while
<span style="color: #000000;">n</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function</lang>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<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)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
<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>
<span style="color: #000000;">still_printing</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<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>
<span style="color: #008080;">while</span> <span style="color: #000000;">still_running</span> <span style="color: #008080;">do</span>
<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>
<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>
<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>
<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>
<span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">still_printing</span> <span style="color: #008080;">then</span>
<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>
<span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"printed"</span>
<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>
<span style="color: #008080;">else</span>
<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>
<span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"size in base"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<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>
<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>
factorial(2):2, calculated in 0.0s, printed in 0.0s
factorial(4):24, calculated in 0s, printed in 0s
factorial(8):40320, calculated in 0s, printed in 0s
factorial(16):20922789888000, calculated in 0s, printed in 0s
factorial(32):263130836933693530167218012160000000, calculated in 0s, printed in 0s
factorial(64):1268869321858841641...4230400000000000000 (90 digits), calculated in 0s, printed in 0s
factorial(128):3856204823625804217...0000000000000000000 (216 digits), calculated in 0s, printed in 0s
factorial(256):8578177753428426541...0000000000000000000 (507 digits), calculated in 0s, printed in 0s
factorial(512):3477289793132605363...0000000000000000000 (1,167 digits), calculated in 0s, printed in 0s
factorial(1024):5418528796058857283...0000000000000000000 (2,640 digits), calculated in 0s, printed in 0s
factorial(2048):1672691931910011705...0000000000000000000 (5,895 digits), calculated in 0s, printed in 0s
factorial(4096):3642736389457041931...0000000000000000000 (13,020 digits), calculated in 0s, printed in 0s
factorial(8192):1275885799409419815...0000000000000000000 (28,504 digits), calculated in 0s, printed in 0s
factorial(16384):1207246711959629373...0000000000000000000 (61,937 digits), calculated in 0s, printed in 0.0s
factorial(32768):9092886296374209477...0000000000000000000 (133,734 digits), calculated in 0s, printed in 0.1s
factorial(65536):5162948523097509165...0000000000000000000 (287,194 digits), calculated in 0.0s, printed in 0.2s
factorial(131072):2358150556532892503...0000000000000000000 (613,842 digits), calculated in 0.0s, printed in 0.8s
factorial(262144):1396355768630047926...0000000000000000000 (1,306,594 digits), calculated in 0.1s, printed in 3.1s
factorial(524288):5578452507102649524...0000000000000000000 (2,771,010 digits), calculated in 0.3s, printed in 13.4s
factorial(1048576):5,857,670 digits, calculated in 0.7s, size in base in 0.2s
factorial(2097152):12,346,641 digits, calculated in 1.7s, size in base in 0.5s
factorial(4194304):25,955,890 digits, calculated in 3.6s, size in base in 1.0s
factorial(8388608):54,436,999 digits, calculated in 8.1s, size in base in 2.2s
factorial(16777216):113,924,438 digits, calculated in 17.7s, size in base in 4.9s
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">/# recursive #/
def factorial
dup 1 > if
dup 1 - factorial *
else
drop 1
endif
enddef
 
/# iterative #/
def factorial2
1 swap for * endfor
enddef
 
0 22 2 tolist for
"Factorial(" print dup print ") = " print factorial2 print nl
endfor</syntaxhighlight>
 
=={{header|PHP}}==
=== Iterative ===
<langsyntaxhighlight lang="php"><?php
function factorial($n) {
if ($n < 0) {
Line 4,007 ⟶ 8,053:
return $factorial;
}
?></langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="php"><?php
function factorial($n) {
if ($n < 0) {
Line 4,023 ⟶ 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 4,050 ⟶ 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 4,086 ⟶ 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 4,100 ⟶ 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 4,115 ⟶ 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 4,162 ⟶ 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===
<syntaxhighlight lang="processing">
int fact(int n){
if(n <= 1){
return 1;
} else{
return n*fact(n-1);
}
}
</syntaxhighlight>
{{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>
 
=={{header|Prolog}}==
{{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 4,186 ⟶ 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 4,202 ⟶ 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 4,216 ⟶ 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 4,232 ⟶ 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
<syntaxhighlight lang="python">from itertools import (accumulate, chain)
from operator import mul
 
# factorial :: Integer
def factorial(n):
return list(
accumulate(chain([1], range(1, 1 + n)), mul)
)[-1]</syntaxhighlight>
 
or including the sequence that got us there:
<syntaxhighlight lang="python">from itertools import (accumulate, chain)
from operator import mul
 
 
# factorials :: [Integer]
def factorials(n):
return list(
accumulate(chain([1], range(1, 1 + n)), mul)
)
 
print(factorials(5))
 
# -> [1, 1, 2, 6, 24, 120]</syntaxhighlight>
 
or
<syntaxhighlight lang="python">from numpy import prod
 
def factorial(n):
return prod(range(1, n + 1), dtype=int)</syntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="python">def factorial(n):
z=1
if n>1:
z=n*factorial(n-1)
return z</syntaxhighlight>
 
{{out}}
<pre>>>> for i in range(6):
Line 4,290 ⟶ 8,587:
5 120
>>></pre>
 
or
<syntaxhighlight lang="python">def factorial(n):
return n * factorial(n - 1) if n else 1</syntaxhighlight>
 
===Numerical Approximation===
The following sample uses Lanczos approximation from [[wp:Lanczos_approximation]] to approximate the gamma function.
 
<lang python>from cmath import *
The gamma function Γ(x) extends the domain of the factorial function, while maintaining the relationship that factorial(x) = Γ(x+1).
<syntaxhighlight lang="python">from cmath import *
 
# Coefficients used by the GNU Scientific Library
Line 4,319 ⟶ 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 4,334 ⟶ 8,637:
factorial(9)=(362880+0j)
</pre>
===Recursive===
<lang python>def factorial(n):
z=1
if n>1:
z=n*factorial(n-1)
return z</lang>
 
=={{header|Q}}==
===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|Quackery}}==
===Iterative===
 
<syntaxhighlight lang="quackery"> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n! )</syntaxhighlight>
 
===Overly Complicated and Inefficient===
 
Words named in the form [Annnnnn] refer to entries in the
The On-Line Encyclopedia of Integer Sequences® [https://oeis.org].
 
<syntaxhighlight lang="quackery"> [ 1 & ] is odd ( n --> b )
 
[ odd not ] is even ( n --> b )
 
[ 1 >> ] is 2/ ( n --> n )
 
[ [] swap
witheach
[ i^ swap - join ] ] is [i^-] ( [ --> [ )
 
[ 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 * factRecall(n - 1)
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight Rlang="r">factIter <- function(n) {
f = 1
forif (in in> 2:n1) f <- f * i{
for (i in 2:n) f <- f * i
}
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))
 
<syntaxhighlight lang="racket">(define (factorial n)
(for/fold ([pro 1]) ([i (in-range 1 (+ n 1))]) (* pro i)))</syntaxhighlight>
 
Or quite simpler by an for/product
 
<syntaxhighlight lang="racket">(define (factorial n)
(for/product ([i (in-range 1 (+ n 1))]) i))</syntaxhighlight>
 
=={{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 4,396 ⟶ 8,777:
кц
Возврат f
Кон Фун</langsyntaxhighlight>
 
=== Recursive ===
<langsyntaxhighlight lang="rapira">Фун Факт(n)
Если n = 1
Возврат 1
Line 4,411 ⟶ 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 4,433 ⟶ 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"
Author: oofoe
Date: 2009-12-10
URL: http://rosettacode.org/wiki/Factorial_function
]
Line 4,498 ⟶ 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 4,512 ⟶ 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}}==
===simple version===
This version of the REXX program calculates the exact value of factorial of numbers up to &nbsp; 25,000.
<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 4,531 ⟶ 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 4,537 ⟶ 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 4,551 ⟶ 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 4,588 ⟶ 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 4,619 ⟶ 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 4,657 ⟶ 9,101:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
</pre>
'''{{out|output'''|text=&nbsp; when using the input isof: &nbsp; &nbsp; <tt> 10000 </tt>}}
 
<pre style="height:30ex">
(Output is shown at &nbsp; <big> '''<sup>4</sup>/<sub>5</sub>''' </big> &nbsp; size.)
<pre style="font-size:80%;height:80ex">
10000! is [35660 digits with 2499 trailing zeroes]:
 
Line 4,719 ⟶ 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 4,727 ⟶ 9,207:
 
func fact nr if nr = 1 return 1 else return nr * fact(nr-1) ok
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
===Iterative===
<syntaxhighlight lang="robotic">
input string "Enter a number:"
set "in" to "('ABS('input')')"
if "in" <= 1 then "one"
set "result" to 1
 
: "factorial"
set "result" to "('result' * 'in')"
dec "in" by 1
if "in" > 1 then "factorial"
* "('result')"
end
 
: "one"
* "1"
end
</syntaxhighlight>
 
=={{header|Rockstar}}==
Here's the "minimized" Rockstar:
<syntaxhighlight lang="rockstar">
Factorial takes a number
If a number is 0
Give back 1.
 
Put a number into the first
Knock a number down
Give back the first times Factorial taking a number
</syntaxhighlight>
 
And here's a more "idiomatic" version:
<syntaxhighlight lang="rockstar">
Real Love takes a heart
A page is a memory.
Put A page over A page into the book
If a heart is nothing
Give back the book
 
Put a heart into my hands
Knock my hands down
Give back a heart of Real Love taking my hands
</syntaxhighlight>
 
=={{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 4,734 ⟶ 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 4,772 ⟶ 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 4,784 ⟶ 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 4,815 ⟶ 9,342:
 
fn factorial_iterative(n: u64) -> u64 {
(1..=n+1).foldproduct(1, |p, n| p*n)
}
 
Line 4,826 ⟶ 9,353:
}
}
</syntaxhighlight>
</lang>
 
=={{header|SASL}}==
Copied from SASL manual, page 3
<syntaxhighlight lang="sasl">
fac 4
where fac 0 = 1
fac n = n * fac (n - 1)
?
</syntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
 
-- recursive
Line 4,848 ⟶ 9,384:
#OUT + fact(a) + " = " + fact_iter(a) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
 
{{libheader|Scala}}
===StraightforwardImperative===
An imperative style using a mutable variable:
This seems in an imperative style but it's converted to functional by a compiler feature called "for comprehension".
<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:
<lang scala>def factorial(n: Int) = if(n == 0) 1 else n * factorial(n-1)</lang>
<syntaxhighlight lang="scala">
def factorial(n: Int): Int =
if (n < 1) 1
else n * factorial(n - 1)
</syntaxhighlight>
 
Using tail recursion with a helper function:
<syntaxhighlight lang="scala">
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)
}
</syntaxhighlight>
 
===Stdlib .product===
Using standard library builtin:
<syntaxhighlight lang="scala">
def factorial(n: Int) = (2 to n).product
</syntaxhighlight>
 
===Folding===
Using folding:
<lang scala>def factorial(n: Int) = (2 to n).foldLeft(1)(_*_) </lang>
<syntaxhighlight lang="scala">
===Using Pimp My Library pattern===
def factorial(n: Int) =
<lang scala>// Note use of big integer support in this version
(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">
implicit def IntToFac(i : Int) = new {
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}
}</lang>
</syntaxhighlight>
 
{{out | Example used in the REPL}}
<pre>
<lang scala>scala> implicit def IntToFac(i : Int) = new {
| def ! = (2 to i).foldLeft(BigInt(1))(_*_)
| }
IntToFac: (i: Int)java.lang.Object{def !: scala.math.BigInt}
 
scala> 20!
res0: scala.math.BigInt = 2432902008176640000
 
scala> 100!
res1: scala.math.BigInt = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</lang>
</pre>
 
=={{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 4,924 ⟶ 9,497:
 
(factorial 8)
;40320</lang>
</syntaxhighlight>
 
=={{header|Scilab}}==
===Built-in===
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</syntaxhighlight>
 
=={{header|Seed7}}==
Seed7 defines the prefix operator [http://seed7.sourceforge.net/libraries/integer.htm#!%28in_integer%29 !] ,
which computes a factorial of an [http://seed7.sourceforge.net/libraries/integer.htm integer].
The maximum representable number forof 32-bitan signed integersinteger is 2147483647.
For 64-bit signed integers the maximum is[http://seed7.sourceforge.net/libraries/integer.htm#(attr_integer)._last 9223372036854775807].
This limits the maximum factorial for 32-bit integers to factorial(1220)=479001600 and2432902008176640000.
for 64-bit integers to factorial(20)=2432902008176640000.
Because of this limitations factorial is a very bad example to show the performance advantage of an iterative solution.
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
const func bigInteger: factorial (in bigInteger: n) is func
result
var bigInteger: fact is 1_;
Line 4,967 ⟶ 9,545:
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: resultfact is 1_;
begin
if n > 1_ then
resultfact := n * factorial(pred(n));
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
 
=={{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 5,012 ⟶ 9,593:
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 5,032 ⟶ 9,612:
end loop;
return v;
end proc;</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">(define factorial
0 -> 1
X -> (* X (factorial (- X 1))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<lang ruby># Recursive:
<syntaxhighlight lang="ruby">func factorial_recursive(n) {
n == 0  ? 1  : (n * __FUNC__(n-1));
}</syntaxhighlight>
}
 
 
Catamorphism:
# Iterative with Array#reduce
<syntaxhighlight lang="ruby">func factorial_reduce(n) {
1..n -> reduce('{|a,b| a *' b }, 1);
}</syntaxhighlight>
}
 
 
# Iterative with Block#repeat:
<syntaxhighlight lang="ruby">func factorial_iterative(n) {
var f = 1;
{|i| f *= i } *<< 2..n;
return f;
}</syntaxhighlight>
}
 
 
# Built-in Number#factorial:
<syntaxhighlight lang="ruby">say 5!</syntaxhighlight>
say 5!;</lang>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="pascal">begin
integer procedure factorial( n );
integer n;
begin
integer fact, i;
fact := 1;
iffor ni >:= 2 step 1 thenuntil n do
for ifact := 2fact step* 1 until n doi;
fact := fact * i;
factorial := fact
end;
integer f; outtext("factorials:"); outimage;
outint( factorial( 6 ), 5);
for f := 0, 1, 2, 6, 9 do begin
outimage
outint(f, 2); outint(factorial(f), 8); outimage
end</lang>
end
end</syntaxhighlight>
{{out}}
<pre>720</pre>factorials:
0 1
1 1
2 2
6 720
9 362880</pre>
 
=={{header|Sisal}}==
Solution using a fold:
<langsyntaxhighlight lang="sisal">define main
 
function main(x : integer returns integer)
Line 5,089 ⟶ 9,675:
end for
 
end function</langsyntaxhighlight>
Simple example using a recursive function:
<langsyntaxhighlight lang="sisal">define main
 
function main(x : integer returns integer)
Line 5,101 ⟶ 9,687:
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 5,112 ⟶ 9,698:
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) ifTrue: [ ^1 ]
ifFalseifTrue: [ |c|^1 ]
ifFalse: [ c := OrderedCollection new.
^ (2 to: self) dofold: [ :ia :b | ca add:* ib ].
^ (c fold: [ :a :b | a * b ] )
]
]
].
 
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}}
<lang smalltalk>| fac |
<syntaxhighlight lang="smalltalk">| fac |
fac := [ :n | (1 to: n) inject: 1 into: [ :prod :next | prod * next ] ].
fac value: 10.
"3628800"</langsyntaxhighlight>
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">fac := [:n | (1 to: n) product].
fac value:40
-> 815915283247897734345611269596115894272000000000</syntaxhighlight>
 
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 5,170 ⟶ 9,789:
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 5,202 ⟶ 9,821:
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}}==
{{works with|BST/BSTC}}
{{works with|FastSpin/FlexSpin}}
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<syntaxhighlight lang="spin">con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | i
ser.start(31, 30, 0, 115200)
 
repeat i from 0 to 10
ser.dec(fac(i))
ser.tx(32)
 
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
 
pub fac(n) : f
f := 1
repeat while n > 0
f *= n
n -= 1</syntaxhighlight>
{{out}}
<pre>1 1 2 6 24 120 720 5040 40320 362880 3628800 </pre>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">fact(n)=
? n!>1, <=1
<= n*fact(n-1)
.</syntaxhighlight>
 
=={{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 5,226 ⟶ 9,934:
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 5,240 ⟶ 9,948:
in
loop (1, 1)
end</langsyntaxhighlight>
 
=={{header|Stata}}==
Mata has the built-in '''factorial''' function. Here are two implementations.
 
<syntaxhighlight lang="stata">mata
real scalar function fact1(real scalar n) {
if (n<2) return(1)
else return(fact1(n-1)*n)
}
 
real scalar function fact2(real scalar n) {
a=1
for (i=2;i<=n;i++) a=a*i
return(a)
}
 
printf("%f\n",fact1(8))
printf("%f\n",fact2(8))
printf("%f\n",factorial(8))</syntaxhighlight>
 
 
 
 
 
=={{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(num_ n: Int) -> Int {
return n < 2 ? 1 : (2...n).reduce(1, *)
}</syntaxhighlight>
 
===Recursive===
return num < 1 ? 1 : reduce(1...num, 1, *)
<syntaxhighlight lang="swift">func factorial(_ n: Int) -> Int {
}</lang>
return n < 2 ? 1 : n * factorial(n - 1)
}</syntaxhighlight>
=={{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">
<lang Swift>func factorial(num: Int) -> Int {
templates factorial
when <=0> do 1 !
return num < 1 ? 1 : num * factorial(num - 1)
when <0..> $ * ($ - 1 -> factorial) !
}</lang>
end factorial
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 5,259 ⟶ 10,058:
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 5,290 ⟶ 10,089:
}
return $sum
}</langsyntaxhighlight>
===Performance Analysis===
<langsyntaxhighlight lang="tcl">puts [ifact 30]
puts [rfact 30]
puts [ifact_caching 30]
Line 5,302 ⟶ 10,101:
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 5,315 ⟶ 10,114:
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 5,348 ⟶ 10,167:
%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}}==
<syntaxhighlight lang="forth">: FACTORIAL
1 SWAP
1 + 1 DO
I * LOOP ;</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
LOOP num=-1,12
IF (num==0,1) THEN
Line 5,374 ⟶ 10,199:
formatnum=CENTER(num,+2," ")
PRINT "factorial of ",formatnum," = ",f
ENDLOOP</langsyntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 5,399 ⟶ 10,224:
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 5,416 ⟶ 10,241:
done
echo "$2"
}</langsyntaxhighlight>
 
If <code>expr</code> uses 32-bit signed integers, then this function overflows after <code>factorial 12</code>.
Line 5,424 ⟶ 10,249:
{{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 5,430 ⟶ 10,255:
done
echo $f
}</langsyntaxhighlight>
 
* bash and zsh use 64-bit signed integers, overflows after <code>factorial 20</code>.
Line 5,437 ⟶ 10,262:
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 5,443 ⟶ 10,268:
else echo $(($1 * $(factorial $(($1-1)) ) ))
fi
}</langsyntaxhighlight>
 
Or in [[Korn Shell|Korn style]]:
Line 5,450 ⟶ 10,275:
{{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 5,469 ⟶ 10,294:
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 5,483 ⟶ 10,311:
return result
end
</syntaxhighlight>
</lang>
===Recursive===
<langsyntaxhighlight lang="ursa">def factorial (int n)
decl int z
set z 1
Line 5,492 ⟶ 10,320:
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|Uxntal}}==
<syntaxhighlight lang="Uxntal">@factorial ( n* -: fact* )
ORAk ?{ POP2 #0001 JMP2r }
DUP2 #0001 SUB2 factorial MUL2
JMP2r</syntaxhighlight>
 
=={{header|Verbexx}}==
<syntaxhighlight lang="verbexx">// ----------------
// recursive method (requires INTV_T input parm)
// ----------------
 
fact_r @FN [n]
{
@CASE
when:(n < 0iv) {-1iv }
when:(n == 0iv) { 1iv }
else: { n * (@fact_r n-1iv) }
};
 
 
// ----------------
// iterative method (requires INTV_T input parm)
// ----------------
 
fact_i @FN [n]
{
@CASE
when:(n < 0iv) {-1iv }
when:(n == 0iv) { 1iv }
else: {
@VAR i fact = 1iv 1iv;
@LOOP while:(i <= n) { fact *= i++ };
}
};
 
// ------------------
// Display factorials
// ------------------
 
@VAR i = -1iv;
@LOOP times:15
{
@SAY «recursive » i «! = » (@fact_r i) between:"";
@SAY «iterative » i «! = » (@fact_i i) between:"";
 
i = 5iv * i / 4iv + 1iv;
};
 
 
/]=========================================================================================
 
Output:
 
recursive -1! = -1
iterative -1! = -1
recursive 0! = 1
iterative 0! = 1
recursive 1! = 1
iterative 1! = 1
recursive 2! = 2
iterative 2! = 2
recursive 3! = 6
iterative 3! = 6
recursive 4! = 24
iterative 4! = 24
recursive 6! = 720
iterative 6! = 720
recursive 8! = 40320
iterative 8! = 40320
recursive 11! = 39916800
iterative 11! = 39916800
recursive 14! = 87178291200
iterative 14! = 87178291200
recursive 18! = 6402373705728000
iterative 18! = 6402373705728000
recursive 23! = 25852016738884976640000
iterative 23! = 25852016738884976640000
recursive 29! = 8841761993739701954543616000000
iterative 29! = 8841761993739701954543616000000
recursive 37! = 13763753091226345046315979581580902400000000
iterative 37! = 13763753091226345046315979581580902400000000
recursive 47! = 258623241511168180642964355153611979969197632389120000000000
iterative 47! = 258623241511168180642964355153611979969197632389120000000000</syntaxhighlight>
 
 
=={{header|Verilog}}==
===Recursive===
<syntaxhighlight lang="verilog">module main;
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>
 
 
=={{header|VHDL}}==
<syntaxhighlight lang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
 
ENTITY Factorial IS
GENERIC (
Nbin : INTEGER := 3 ; -- number of bit to input number
Nbou : INTEGER := 13) ; -- number of bit to output factorial
PORT (
clk : IN STD_LOGIC ; -- clock of circuit
sr : IN STD_LOGIC_VECTOR(1 DOWNTO 0); -- set and reset
N : IN STD_LOGIC_VECTOR(Nbin-1 DOWNTO 0) ; -- max number
Fn : OUT STD_LOGIC_VECTOR(Nbou-1 DOWNTO 0)); -- factorial of "n"
END Factorial ;
 
ARCHITECTURE Behavior OF Factorial IS
---------------------- Program Multiplication --------------------------------
FUNCTION Mult ( CONSTANT MFa : IN UNSIGNED ;
CONSTANT MI : IN UNSIGNED ) RETURN UNSIGNED IS
VARIABLE Z : UNSIGNED(MFa'RANGE) ;
VARIABLE U : UNSIGNED(MI'RANGE) ;
BEGIN
Z := TO_UNSIGNED(0, MFa'LENGTH) ; -- to obtain the multiplication
U := MI ; -- regressive counter
LOOP
Z := Z + MFa ; -- make multiplication
U := U - 1 ;
EXIT WHEN U = 0 ;
END LOOP ;
RETURN Z ;
END Mult ;
-------------------Program Factorial ---------------------------------------
FUNCTION Fact (CONSTANT Nx : IN NATURAL ) RETURN UNSIGNED IS
VARIABLE C : NATURAL RANGE 0 TO 2**Nbin-1 ;
VARIABLE I : UNSIGNED(Nbin-1 DOWNTO 0) ;
VARIABLE Fa : UNSIGNED(Nbou-1 DOWNTO 0) ;
BEGIN
C := 0 ; -- counter
I := TO_UNSIGNED(1, Nbin) ;
Fa := TO_UNSIGNED(1, Nbou) ;
LOOP
EXIT WHEN C = Nx ; -- end loop
C := C + 1 ; -- progressive couter
Fa := Mult (Fa , I ); -- call function to make a multiplication
I := I + 1 ; --
END LOOP ;
RETURN Fa ;
END Fact ;
--------------------- Program TO Call Factorial Function ------------------------------------------------------
TYPE Table IS ARRAY (0 TO 2**Nbin-1) OF UNSIGNED(Nbou-1 DOWNTO 0) ;
FUNCTION Call_Fact RETURN Table IS
VARIABLE Fc : Table ;
BEGIN
FOR c IN 0 TO 2**Nbin-1 LOOP
Fc(c) := Fact(c) ;
END LOOP ;
RETURN Fc ;
END FUNCTION Call_Fact;
CONSTANT Result : Table := Call_Fact ;
------------------------------------------------------------------------------------------------------------
SIGNAL Nin : STD_LOGIC_VECTOR(N'RANGE) ;
BEGIN -- start of architecture
 
 
Nin <= N WHEN RISING_EDGE(clk) AND sr = "10" ELSE
(OTHERS => '0') WHEN RISING_EDGE(clk) AND sr = "01" ELSE
UNAFFECTED;
 
Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;
 
END Behavior ;</syntaxhighlight>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">function! Factorial(n)
if a:n < 2
return 1
Line 5,514 ⟶ 10,529:
return a:n * Factorial(a:n-1)
endif
endfunction</langsyntaxhighlight>
 
=={{header|VBScriptV (Vlang)}}==
Updated to V (Vlang) version 0.2.2
Optimized with memoization, works for numbers up to 170 (because of the limitations on Doubles), exits if -1 is input
===Imperative===
<lang VBScript>Dim lookupTable(170), returnTable(170), currentPosition, input
<syntaxhighlight lang="go">const max_size = 10
currentPosition = 0
 
fn factorial_i() {
Do While True
mut facs := [0].repeat(max_size + 1)
input = InputBox("Please type a number (-1 to quit):")
facs[0] = 1
MsgBox "The factorial of " & input & " is " & factorial(CDbl(input))
println('The 0-th Factorial number is: 1')
Loop
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() {
Function factorial (x)
factorial_i()
If x = -1 Then
}</syntaxhighlight>
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
 
===Recursive===
Function lookup (x)
<syntaxhighlight lang="go">const max_size = 10
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
 
fn factorial_r(n int) int {
Function store (x, y)
if n == 0 {
lookupTable(currentPosition) = x
return 1
returnTable(currentPosition) = y
}
currentPosition = currentPosition + 1
return n * factorial_r(n - 1)
End Function</lang>
}
 
fn main() {
=={{header|VHDL}}==
for i := 0; i <= max_size; i++ {
<lang VHDL>use std.textio.all;
println('factorial($i) is: ${factorial_r(i)}')
}
}</syntaxhighlight>
 
===Tail Recursive===
entity rc is
<syntaxhighlight lang="go">const max_size = 10
end entity rc;
 
fn factorial_tail(n int) int {
architecture beh of rc is
sum := 1
function fact(n:integer) return integer is
return factorial_r(n, sum)
variable f: integer := 1;
}
variable i: integer;
begin
for i in 2 to n loop
f := f*i;
end loop;
return f;
end;
 
fn factorial_r(n int, sum int) int {
begin
if n == 0 {
process
variablereturn i: integer;sum
}
variable l: line;
return factorial_r(n - 1, n * sum )
begin
}
for i in 0 to 5 loop
 
write(l, i);
fn main() {
write(l, string'(" "));
for i := 0; i <= write(l,max_size; fact(i));++ {
println('factorial($i) is: ${factorial_tail(i)}')
writeline(output, l);
}
end loop;
}</syntaxhighlight>
wait;
 
end process;
===Memoized===
end;</lang>
<syntaxhighlight lang="go">const max_size = 10
 
struct Cache {
mut:
values []int
}
 
fn fac_cached(n int, 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) }
cache.values << fac_n
return fac_n
}
 
fn main() {
mut cache := Cache{}
for n := 0; n <= max_size; n++ {
fac_n := fac_cached(n, mut cache)
println('The $n-th Factorial is: $fac_n')
}
}</syntaxhighlight>
{{out}}
<pre>The 0-th Factorial is: 1
<pre>
The 1-th Factorial is: 1
0 1
The 2-th Factorial is: 2
1 1
The 3-th Factorial is: 6
2 2
The 4-th Factorial is: 24
3 6
The 5-th Factorial is: 120
4 24
The 6-th Factorial is: 720
5 120
The 7-th Factorial is: 5040
</pre>
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 5,629 ⟶ 10,654:
 
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">
(module
;; recursive
(func $fac (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.mul
end)
(export "fac" (func $fac)))
</syntaxhighlight>
 
<syntaxhighlight lang="webassembly">
(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">
(module
;; 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">
(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">
(module
;; iterative, generated by C compiler (LLVM) from recursive code!
(func $factorial (export "factorial") (param $p0 i32) (result i32)
(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 5,661 ⟶ 10,803:
 
[[!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 5,684 ⟶ 10,856:
mul ecx
loop .factor
ret</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="asm">global fact
section .text
 
Line 5,705 ⟶ 10,877:
; base case: return 1
mov eax, 1
ret</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="asm">global factorial
section .text
 
Line 5,723 ⟶ 10,895:
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}}==
<syntaxhighlight lang="lisp">(defun factorial (x)
(if (< x 0)
nil
(if (<= x 1)
1
(* x (factorial (- x 1))) ) ) )</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func FactIter(N); \Factorial of N using iterative method
int N; \range: 0..12
int F, I;
Line 5,740 ⟶ 10,920:
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|YAMLScript}}==
<syntaxhighlight lang="yaml">
#!/usr/bin/env ys-0
 
defn main(n):
say: "$n! = $factorial(n)"
 
defn factorial(x):
apply *: 2 .. x
</syntaxhighlight>
 
=={{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 5,757 ⟶ 10,990:
</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>
5

edits