Factorial: Difference between revisions
Content deleted Content added
PascalABC.NET |
|||
(331 intermediate revisions by more than 100 users not shown) | |||
Line 27:
This is an iterative solution which outputs the factorial of each number supplied on standard input.
<
|~ Read n,
#:end: if n is 0 terminates
Line 37:
{+% Dequeue incidental 0, add to get Y into Z, output fac(n).
<:a:~$ Output a newline.
^:r:</
{{out}}
Line 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.
<
USING FACTO,R13
SAVEAREA B STM-SAVEAREA(R15)
Line 65 ⟶ 86:
L R15,=A(FACT)
BALR R14,R15 call fact(n)
DUMP EQU *
MVC WTOBUF+5(2),S+30
MVC WTOBUF+9(32),S
WTO MF=(E,WTOMSG)
ENDLOOPN EQU *
RETURN EQU *
Line 90 ⟶ 111:
LOOP CP I,L if i>l
BH ENDLOOP then goto endloop
ENDLOOP EQU *
LA R1,R return r
Line 113 ⟶ 134:
LTORG
YREGS
END FACTO</
{{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===
<
data: lv_res type i value 1.
do iv_val times.
Line 126 ⟶ 349:
iv_val = lv_res.
endform.</
===Recursive===
<
data: lv_temp type i.
Line 138 ⟶ 361:
multiply iv_val by lv_temp.
endif.
endform.</
=={{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===
<
{
if (n < 0)
Line 152 ⟶ 446:
return fact;
}</
===Recursive===
<
{
if (n < 0)
Line 163 ⟶ 457:
return n * factorial(n - 1);
}</
=={{header|Ada}}==
===Iterative===
<
Result : Positive := N;
Counter : Natural := N - 1;
Line 175 ⟶ 469:
end loop;
return Result;
end Factorial;</
===Recursive===
<
Result : Positive := 1;
begin
Line 184 ⟶ 478:
end if;
return Result;
end Factorial;</
===Numerical Approximation===
<
with Ada.Numerics.Generic_Complex_Elementary_Functions;
with Ada.Numerics.Generic_Elementary_Functions;
Line 247 ⟶ 541:
New_Line;
end loop;
end Factorial_Numeric_Approximation;</
{{out}}
<pre>
Line 262 ⟶ 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===
<
factorial(integer n)
{
Line 278 ⟶ 582:
return result;
}</
=={{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===
<
LONG LONG INT z := 1;
FOR n TO upb n DO z *:= n OD;
z
); ~</
===Numerical Approximation===
Line 292 ⟶ 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''}}
<
[]REAL p = []REAL(0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
Line 322 ⟶ 647:
OD
)
</syntaxhighlight>
{{out}}
<pre>
Line 338 ⟶ 663:
===Recursive===
<
CASE n+1 IN
1,1,2,6,24,120,720 # a brief lookup #
Line 344 ⟶ 669:
n*factorial(n-1)
ESAC
; ~</
=={{header|ALGOL W}}==
Iterative solution
<
% computes factorial n iteratively %
integer procedure factorial( integer value n ) ;
Line 372 ⟶ 687:
for t := 0 until 10 do write( "factorial: ", t, factorial( t ) );
end.</
=={{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:
<
PROC main()
WriteF('5! = \d\n', fact(5))
ENDPROC</
Iterative:
<
DEF r, y
IF x < 2 THEN RETURN 1
r := 1; y := x;
FOR x := 2 TO y DO r := r * x
ENDPROC r</
=={{header|AntLang}}==
AntLang is a functional language, but it isn't made for recursion - it's made for list processing.
<
=={{header|Apex}}==
===Iterative===
<
if (n < 0) {
System.debug('No negative numbers');
Line 406 ⟶ 731:
}
return ans;
}</
===Recursive===
<
if (n < 0){
System.debug('No negative numbers');
Line 414 ⟶ 739:
}
return (n < 2) ? 1 : n * fact(n - 1);
}</
=={{header|APL}}==
Both GNU APL and the DYALOG dialect of APL provides a factorial function:
<
720</
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:
<
And the resulting function can then be used instead of the (admittedly more convenient) builtin one:
<
720</
{{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===
<
if x < 0 then return 0
set R to 1
Line 435 ⟶ 767:
end repeat
return R
end factorial</
===Recursion===
Line 442 ⟶ 774:
(Perhaps because the iterative code is making use of list splats)
<
on factorial(x)
if x > 1 then
x * (factorial(x - 1))
else
end if
end factorial</
===Fold===
We can also define factorial as '''
where product is defined in terms of a fold.
<
-- factorial :: Int -> Int
on factorial(x)
end factorial
on run
Line 480 ⟶ 807:
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m
set
repeat with i from m to n
set end of xs to i
end repeat
xs
else
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 507 ⟶ 834:
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
Line 518 ⟶ 846:
end script
end if
end mReturn
-- product :: [Num] -> Num
on product(xs)
script multiply
on |λ|(a, b)
a * b
end |λ|
end script
foldl(multiply, 1, xs)
end product</syntaxhighlight>
{{Out}}
<pre>39916800</pre>
=={{header|Arendelle}}==
Line 556 ⟶ 876:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 735 ⟶ 1,055:
</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">
/---------*--~-$#-&
| /--;---\| [!]-\
Line 747 ⟶ 1,134:
*-------+-</
\-#0----/
</syntaxhighlight>
=={{header|ATS}}==
===Iterative===
<syntaxhighlight lang="ats">
fun
fact
Line 763 ⟶ 1,150:
val () = while (n > 0) (res := res * n; n := n - 1)
}
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="ats">
fun
factorial
Line 772 ⟶ 1,159:
if n > 0 then n * factorial(n-1) else 1
// end of [factorial]
</syntaxhighlight>
===Tail-recursive===
<syntaxhighlight lang="ats">
fun
factorial
Line 784 ⟶ 1,171:
loop(n, 1)
end // end of [factorial]
</syntaxhighlight>
=={{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===
<
factorial(n)
Line 796 ⟶ 1,196:
result *= A_Index
Return result
}</
===Recursive===
<
factorial(n)
{
return n > 1 ? n-- * factorial(n) : 1
}</
=={{header|AutoIt}}==
===Iterative===
<
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
Line 819 ⟶ 1,219:
Next
Return $fact
EndFunc</
===Recursive===
<
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
Line 830 ⟶ 1,230:
EndIf
return $int * factorial($int - 1)
EndFunc</
=={{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'''
<
{
if ( n <= 1 ) return 1;
return n*fact_r(n-1);
}</
'''Iterative'''
<
{
if ( n < 1 ) return 1;
Line 849 ⟶ 1,263:
}
return r
}</
=={{header|Axe}}==
'''Iterative'''
<
1→R
For(I,1,r₁)
Line 859 ⟶ 1,273:
End
R
Return</
'''Recursive'''
<
r₁??1,r₁*FACT(r₁-1)
Return</
=={{header|Babel}}==
===Iterative===
<
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
Line 879 ⟶ 1,292:
{dup 1 =}{ zap 1 }
{1 }{ <- 1 {iter 1 + *} -> 1 - times })
cond}))</
===Recursive===
<
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
Line 892 ⟶ 1,305:
{1 }{ dup 1 - fact ! *})
cond}))
</syntaxhighlight>
When run, either code snippet generates the following
Line 908 ⟶ 1,321:
362880
3628800</pre>
=={{header|bash}}==
===Recursive===
<
{
if [ $1 -le 1 ]
Line 941 ⟶ 1,334:
fi
}
</syntaxhighlight>
===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}}
<
DIM f AS Integer, i AS Integer
f = 1
Line 954 ⟶ 1,364:
NEXT i
factorial = f
END FUNCTION</
===Recursive===
{{works with|FreeBASIC}}
{{works with|QBasic}}
{{works with|RapidQ}}
<
IF n < 2 THEN
factorial = 1
Line 965 ⟶ 1,376:
factorial = n * factorial(n-1)
END IF
END FUNCTION</
==={{header|Applesoft BASIC}}===
====Iterative====
<syntaxhighlight lang="applesoftbasic">100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END
200 N = INT(N)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
220 RETURN</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="applesoftbasic"> 10 A = 768:L = 7
20 DATA 165,157,240,3
30 DATA 32,149,217,96
40 FOR I = A TO A + L
50 READ B: POKE I,B: NEXT
60 H = 256: POKE 12,A / H
70 POKE 11,A - PEEK (12) * H
80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1)
90 PRINT FN FA(4)</syntaxhighlight>http://hoop-la.ca/apple2/2013/usr-if-recursive-fn/
==={{header|BaCon}}===
Overflow occurs at 21 or greater. Negative values treated as 0.
<syntaxhighlight lang="freebasic">' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n"</syntaxhighlight>
{{out}}
<pre>prompt$ ./factorial 0
0! = 1
prompt$ ./factorial 20
20! = 2432902008176640000</pre>
==={{header|BASIC256}}===
====Iterative====
<syntaxhighlight lang="vb">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
factorial = 1
if n > 0 then
for p = 1 to n
factorial *= p
next p
end if
end function</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="basic256">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
if n > 0 then
factorial = n * factorial(n-1)
else
factorial = 1
end if
end function</syntaxhighlight>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
18! is the largest that doesn't overflow.
<syntaxhighlight lang="bbcbasic"> *FLOAT64
@% = &1010
PRINT FNfactorial(18)
END
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)</syntaxhighlight>
{{out}}
<pre>6402373705728000</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
====Iterative====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factoriali(i)
140 next i
150 sub factoriali(n) : 'Iterative
160 f = 1
170 if n > 1 then
180 for j = 2 to n
190 f = f*j
200 next j
210 endif
220 factoriali = f
230 end sub</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factorialr(i)
140 next i
150 sub factorialr(n) : 'Recursive
160 if n < 2 then
170 f = 1
180 else
190 f = n*factorialr(n-1)
200 endif
210 factorialr = f
220 end sub</syntaxhighlight>
==={{header|Commodore BASIC}}===
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
40 PRINT N;"! =";F
50
100 REM FACTORIAL CALC USING SIMPLE LOOP
110 F = 1
Line 978 ⟶ 1,507:
130 F = F*I
140 NEXT
150 RETURN</
====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}}===
<
110 LET F=1
120 FOR I=2 TO N
Line 987 ⟶ 1,695:
140 NEXT
150 LET FACT=F
160 END DEF</
==={{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====
<
20 LET FACT=1
30 FOR I=2 TO N
40 LET FACT=FACT*I
50 NEXT I
60 PRINT FACT</
{{in}}
<pre>13</pre>
Line 1,003 ⟶ 1,941:
====Recursive====
A <code>GOSUB</code> is just a procedure call that doesn't pass parameters.
<
20 LET FACT=1
30 GOSUB 60
Line 1,012 ⟶ 1,950:
80 LET N=N-1
90 GOSUB 60
100 RETURN</
{{in}}
<pre>13</pre>
Line 1,018 ⟶ 1,956:
<pre>6227020800</pre>
==={{header|
<syntaxhighlight lang="qbasic">
n = 10
for ii =
next
</syntaxhighlight>
===
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
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}}==
<
set /p x=
set /a fs=%x%-1
Line 1,055 ⟶ 2,301:
echo %y%
pause
exit</
=={{header|bc}}==
<
define f(x) {
Line 1,078 ⟶ 2,310:
}
f(1000)
quit</
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program Factorial
// only works for cardinal numbers 0..N
calc main_init
log to_str(Iterative(4)) // 24
log to_str(Recursive(5)) // 120
calc Iterative(
n:num -- number of iterations
):num -- result
var total = 1
loop from:2 to:n index:ix
total = ix * total
return total
calc Recursive ditto
if n <= 1
return 1
else
return n * Recursive(n-1)</syntaxhighlight>
{{out}}
<pre>24
120</pre>
=={{header|beeswax}}==
Line 1,085 ⟶ 2,340:
Infinite loop for entering <code>n</code> and getting the result <code>n!</code>:
<
_>1FT"pF>M"p~.~d
>Pd >~{Np
d <</
Calculate <code>n!</code> only once:
<
_1FT"pF>M"p~.~d
>Pd >~{;</
Limits for UInt64 numbers apply to both examples.
Line 1,101 ⟶ 2,356:
<code>i</code> indicates that the program expects the user to enter an integer.
<
i0
1
Line 1,113 ⟶ 2,368:
3628800
i22
17196083355034583040</
Input of negative numbers forces the program to quit with an error message.
=={{header|Befunge}}==
<
^-1:_$>\:|
@.$<</
=={{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
<
=
. !arg:0&1
Line 1,151 ⟶ 2,414:
$ 10
: 3628800
</syntaxhighlight>
This recursive lambda function is made in the following way (see http://en.wikipedia.org/wiki/Lambda_calculus):
Line 1,162 ⟶ 2,425:
or, translated to Bracmat, and computing 10!
<
& (!g$!g):?f
& !f$10
)</
The following is a straightforward recursive solution. Stack overflow occurs at some point, above 4243! in my case (Win XP).
Line 1,176 ⟶ 2,439:
Lastly, here is an iterative solution
<
r
. !arg:?r
Line 1,182 ⟶ 2,445:
' (!arg:>1&(!arg+-1:?arg)*!r:?r)
& !r
);</
factorial$5000
Line 1,189 ⟶ 2,452:
=={{header|Brainf***}}==
Prints sequential factorials in an infinite loop.
<
+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-
]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[
>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]</
=={{header|Brat}}==
<
true? x == 0 1 { x * factorial(x - 1)}
}</
=={{header|Bruijn}}==
Implementation for numbers encoded in balanced ternary using Mixfix syntax defined in the Math module:
<syntaxhighlight lang="bruijn">
:import std/Math .
factorial [∏ (+1) → 0 | [0]]
:test ((factorial (+10)) =? (+3628800)) ([[1]])
</syntaxhighlight>
=={{header|Burlesque}}==
Line 1,203 ⟶ 2,478:
Using the builtin ''Factorial'' function:
<
blsq ) 6?!
720
</syntaxhighlight>
Burlesque does not have functions nor is it iterative. Burlesque's strength are its implicit loops.
Line 1,212 ⟶ 2,487:
Following examples display other ways to calculate the factorial function:
<
blsq ) 1 6r@pd
720
Line 1,225 ⟶ 2,500:
blsq ) 7ro)(.*){0 1 11}die!
720
</syntaxhighlight>
=={{header|C}}==
=== Iterative ===
<
int result = 1;
for (int i = 1; i <= n; ++i)
Line 1,246 ⟶ 2,510:
return result;
}
</syntaxhighlight>
Handle negative n (returning -1)
<
int result = 1;
if(n<0)
Line 1,258 ⟶ 2,522:
return result;
}
</syntaxhighlight>
=== Recursive ===
<
return n == 0 ? 1 : n * factorial(n - 1);
}
</syntaxhighlight>
Handle negative n (returning -1).
<
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)
<
return n < 1 ? acc : fac_aux(n - 1, acc * n);
}
Line 1,285 ⟶ 2,549:
int factorial(int n) {
return fac_aux(n, 1);
}</
===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>
Line 1,331 ⟶ 2,595:
19,"\n%04d") ):"%4d",l1-> lll[l] ) ; }
ll1ll(10); }
</syntaxhighlight>
=={{header|C sharp|C#}}==
===Iterative===
<
class Program
Line 1,356 ⟶ 2,620:
Console.WriteLine(Factorial(10));
}
}</
===Recursive===
<
class Program
Line 1,374 ⟶ 2,638:
Console.WriteLine(Factorial(10));
}
}</
===Tail Recursive===
<
class Program
Line 1,402 ⟶ 2,666:
Console.WriteLine(Factorial(10));
}
}</
===Functional===
<
using System.Linq;
Line 1,418 ⟶ 2,682:
Console.WriteLine(Factorial(10));
}
}</
===Arbitrary Precision===
{{libheader|System.Numerics}}
<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;
Line 1,435 ⟶ 2,712:
{
return Enumerable.Range(1, number).Aggregate(new BigInteger(1), (acc, num) => acc * num);
}
static public BI FactorialQ(int number) // functional quick, uses prodtree method
{
var s = Enumerable.Range(1, number).Select(num => new BI(num)).ToArray();
int top = s.Length, nt, i, j;
while (top > 1) {
for (i = 0, j = top, nt = top >> 1; i < nt; i++) s[i] *= s[--j];
top = nt + ((top & 1) == 1 ? 1 : 0);
}
return s[0];
}
Line 1,441 ⟶ 2,729:
Console.WriteLine(Factorial(250));
}
}</
{{out}}
<pre>3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000</pre>
Line 1,447 ⟶ 2,735:
=={{header|C++}}==
The C versions work unchanged with C++, however, here is another possibility using the STL and boost:
<
#include <algorithm>
Line 1,454 ⟶ 2,742:
// last is one-past-end
return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}</
===Iterative===
This version of the program is iterative, with a
<syntaxhighlight lang="cpp">//iteration with while
long long int factorial(long long int n)
{
while(1<n)
return
}</syntaxhighlight>
===Template===
<
struct Factorial
{
Line 1,492 ⟶ 2,774:
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}</
===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:
<
{ dup 1 <= [pop 1] [dec rec_fac *] if }</
=={{header|Ceylon}}==
<
Integer? recursiveFactorial(Integer n) =>
Line 1,520 ⟶ 2,954:
}
}
</syntaxhighlight>
=={{header|Chapel}}==
<
var r = 1;
for i in 1..n do
Line 1,529 ⟶ 2,963:
return r;
}</
=={{header|Chef}}==
<
Only reads one value.
Line 1,548 ⟶ 2,982:
Pour contents of the 1st mixing bowl into the 1st baking dish.
Serves 1.</
=={{header|ChucK}}==
===Recursive===
<syntaxhighlight lang="c">
0 => int total;
fun int factorial(int i)
Line 1,563 ⟶ 2,997:
return total;
}
// == 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,576 ⟶ 3,024:
return total;
}
</syntaxhighlight>
=={{header|Clay}}==
Obviously there’s more than one way to skin a cat. Here’s a selection — recursive, iterative, and “functional” solutions.
<
if (n == 0) return 1;
return n * factorialRec(n - 1);
Line 1,593 ⟶ 3,041:
factorialFold(n) {
return reduce(multiply, 1, range(1, n + 1));
}</
We could also do it at compile time, because — hey — why not?
<
overload factorialStatic(static 0) = 1;</
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).
<
if (n == 0) return N(1);
return n * factorial(n - 1);
}</
And testing:
<
println(factorialRec(5)); // 120
println(factorialIter(5)); // 120
Line 1,615 ⟶ 3,063:
println(factorialStatic(static 5)); // 120
println(factorial(Int64(20))); // 2432902008176640000
}</
=={{header|Clio}}==
=== Recursive ===
<
fn factorial n:
if n <= 1: n
Line 1,637 ⟶ 3,075:
10 -> factorial -> print
</syntaxhighlight>
=={{header|CLIPS}}==
<syntaxhighlight lang="lisp"> (deffunction factorial (?a)
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
else
(if (= ?a 0) then
1
else
(* ?a (factorial (- ?a 1))))))</syntaxhighlight>
=={{header|Clojure}}==
=== Folding ===
<
(apply *' (range 2 (inc x))))</
=== Recursive ===
<
(if (< x 2)
1
(*' x (factorial (dec x)))))</
=== Tail recursive ===
<
(loop [x x
acc 1]
(if (< x 2)
acc
(recur (dec x) (*' acc x)))))</
=== 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}}==
<
set(product 1)
foreach(i RANGE 2 ${n})
Line 1,669 ⟶ 3,154:
factorial(f 12)
message("12! = ${f}")</
=={{header|COBOL}}==
Line 1,676 ⟶ 3,161:
=== Intrinsic Function ===
COBOL includes an intrinsic function which returns the factorial of its argument.
<
=== Iterative ===
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. factorial_iterative.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(
LINKAGE SECTION.
01 n PIC 9(
01 ret PIC 9(
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.
END FUNCTION factorial_iterative.
</syntaxhighlight>
=== Recursive ===
{{works with|Visual COBOL}}
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. factorial_recursive.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 prev-n PIC 9(
LINKAGE SECTION.
01 n PIC 9(
01 ret PIC 9(
PROCEDURE DIVISION USING BY VALUE n RETURNING ret.
IF n = 0
Line 1,718 ⟶ 3,207:
ELSE
SUBTRACT 1 FROM n GIVING prev-n
MULTIPLY n BY
END-IF
GOBACK.
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,728 ⟶ 3,265:
=== Recursive ===
<
if n <= 1
1
else
n * fac n-1</
=== Functional ===
{{works with|JavaScript|1.8}} (See [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce MDC])
<
[1..n].reduce (x,y) -> x*y</
=={{header|Comal}}==
Recursive:
<
r:=1
IF n>1 THEN
Line 1,747 ⟶ 3,284:
ENDIF
RETURN r
ENDPROC Recursive</
=={{header|Comefrom0x10}}==
Line 1,753 ⟶ 3,290:
This is iterative; recursion is not possible in Comefrom0x10.
<
acc = 1
Line 1,767 ⟶ 3,304:
n = n - 1
acc # prints the result</
=={{header|Common Lisp}}==
Recursive:
<
(if (zerop n) 1 (* n (factorial (1- n)))))</
or
<syntaxhighlight lang="lisp">(defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))))</syntaxhighlight>
Tail Recursive:
<
(if (zerop n) m (factorial (1- n) (* m n))))</
Iterative:
<
"Calculates N!"
(loop for result = 1 then (* result i)
for i from 2 to n
finally (return result)))</
Functional:
<
(reduce #'* (loop for i from 1 to n collect i)))</
===Alternate solution===
<syntaxhighlight lang="lisp">;; Project : Factorial
(defun factorial (n)
Line 1,799 ⟶ 3,340:
(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===
<
BRZ done_i ; 0! = 1
Line 1,851 ⟶ 3,389:
n: 0
x: 5</
===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!.
<
ADD x
STA load
Line 1,869 ⟶ 3,407:
120
x: 5</
=={{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===
<
in {
assert(n <= 12);
Line 1,891 ⟶ 3,456:
// Computed and printed at run-time.
12.factorial.writeln;
}</
{{out}}
<pre>479001600u
Line 1,897 ⟶ 3,462:
===Recursive Version===
<
in {
assert(n <= 12);
Line 1,915 ⟶ 3,480:
// Computed and printed at run-time.
12.factorial.writeln;
}</
(Same output.)
===Functional Version===
<
uint factorial(in uint n) pure nothrow @nogc
Line 1,934 ⟶ 3,499:
// Computed and printed at run-time.
12.factorial.writeln;
}</
(Same output.)
===Tail Recursive (at run-time, with DMD) Version===
<
in {
assert(n <= 12);
Line 1,959 ⟶ 3,524:
// Computed and printed at run-time.
12.factorial.writeln;
}</
(Same output.)
=={{header|Dart}}==
===Recursive===
<
if(n<0) {
throw new IllegalArgumentException('Argument less than 0');
Line 1,974 ⟶ 3,539:
print(fact(10));
print(fact(-1));
}</
===Iterative===
<
if(n<0) {
throw new IllegalArgumentException('Argument less than 0');
Line 1,990 ⟶ 3,555:
print(fact(10));
print(fact(-1));
}</
=={{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.
<
* (n) lfx -- (factorial of n)
*]sz
Line 2,012 ⟶ 3,577:
* For example, print the factorial of 50.
*]sz
50 lfx psz</
=={{header|Delphi}}==
===Iterative===
<
{$APPTYPE CONSOLE}
Line 2,046 ⟶ 3,596:
begin
Writeln('5! = ', FactorialIterative(5));
end.</
===Recursive===
<
{$APPTYPE CONSOLE}
Line 2,063 ⟶ 3,613:
begin
Writeln('5! = ', FactorialRecursive(5));
end.</
===Tail Recursive===
<
{$APPTYPE CONSOLE}
Line 2,089 ⟶ 3,639:
begin
Writeln('5! = ', FactorialTailRecursive(5));
end.</
=={{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===
<
var
i : Integer;
Line 2,101 ⟶ 3,697:
for i := 2 to n do
Result *= i;
end;</
===Recursive===
<
begin
if n>1 then
Result := RecursiveFactorial(n-1)*n
else Result := 1;
end;</
=={{header|Dyalect}}==
<
if n < 2 {
1
Line 2,118 ⟶ 3,714:
n * factorial(n - 1)
}
}</
=={{header|Dylan}}==
=== Functional ===
<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}}==
<
def factorial(n) {
return accum 1 for i in 2..n { _ * i }
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
func factorial n .
return r
.
</syntaxhighlight>
=={{header|EchoLisp}}==
===Iterative===
<
(define (fact n)
(for/product ((f (in-range 2 (1+ n)))) f))
(fact 10)
→ 3628800
</syntaxhighlight>
===Recursive with memoization===
<
(define (fact n)
(if (zero? n) 1
Line 2,160 ⟶ 3,835:
(fact 10)
→ 3628800
</syntaxhighlight>
===Tail recursive===
<
(define (fact n (acc 1))
(if (zero? n) acc
Line 2,168 ⟶ 3,843:
(fact 10)
→ 3628800
</syntaxhighlight>
===Primitive===
<
(factorial 10)
→ 3628800
</syntaxhighlight>
===Numerical approximation===
<
(lib 'math)
math.lib v1.13 ® EchoLisp
(gamma 11)
→ 3628800.0000000005
</syntaxhighlight>
=={{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">
function fact(n int in) returns (bigint)
if (n < 0)
Line 2,196 ⟶ 3,994:
return (ans);
end
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="egl">
function fact(n int in) returns (bigint)
if (n < 0)
Line 2,210 ⟶ 4,008:
end
end
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
note
description: "recursive and iterative factorial example of a positive integer."
Line 2,264 ⟶ 4,062:
end
</syntaxhighlight>
=={{header|Ela}}==
Tail recursive version:
<
where fact' acc 0 = acc
fact' acc n = fact' (n * acc) (n - 1)</
=={{header|Elixir}}==
<
# Simple recursive function
def fac(0), do: 1
Line 2,298 ⟶ 4,096:
def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)
end</
=={{header|Elm}}==
===
<
factorial : Int -> Int
factorial n =
if n < 1 then 1 else n*factorial(n-1)
</syntaxhighlight>
===
<
factorialAux : Int -> Int -> Int
factorialAux a acc =
Line 2,320 ⟶ 4,118:
factorial a =
factorialAux a 1
</syntaxhighlight>
===
<
import List exposing (product, range)
Line 2,330 ⟶ 4,128:
factorial a =
product (range 1 a)
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<syntaxhighlight lang
;; Functional (most elegant and best suited to Lisp dialects):
(defun fact (n)
"Return the factorial of integer N, which require to be positive or 0."
;; Elisp won't do any type checking automatically, so
;; good practice would be doing that ourselves:
(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">
;; 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>.
<
(calc-eval "fact(30)")
=>
"265252859812191058636308480000000"</
=={{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:
<
With a recursive function:
<
fac(N) -> N * fac(N-1).</
With a tail-recursive function:
<
fac(1,N) -> N;
fac(I,N) -> fac(I-1,N*I).</
=={{header|ERRE}}==
Line 2,366 ⟶ 4,233:
'''Iterative procedure:'''
<syntaxhighlight lang="erre">
PROCEDURE FACTORIAL(X%->F)
F=1
Line 2,375 ⟶ 4,242:
END IF
END PROCEDURE
</syntaxhighlight>
'''Recursive procedure:'''
<syntaxhighlight lang="erre">
PROCEDURE FACTORIAL(FACT,X%->FACT)
IF X%>1 THEN FACTORIAL(X%*FACT,X%-1->FACT)
END IF
END PROCEDURE
</syntaxhighlight>
Procedure call is for example FACTORIAL(1,5->N)
Line 2,389 ⟶ 4,256:
Straight forward methods
===Iterative===
<
atom f = 1
while n > 1 do
Line 2,397 ⟶ 4,264:
return f
end function</
===Recursive===
<
if n > 1 then
return factorial(n-1) * n
Line 2,406 ⟶ 4,273:
return 1
end if
end function</
===Tail Recursive===
{{works with|Euphoria|4.0.0}}
<
if n <= 0 then
return acc
Line 2,416 ⟶ 4,283:
return factorial(n-1, n*acc)
end if
end function</
==='Paper tape' / Virtual Machine version===
Line 2,422 ⟶ 4,289:
Another 'Paper tape' / Virtual Machine version, with as much as possible happening in the tape itself. Some command line handling as well.
<
enum MUL_LLL,
Line 2,527 ⟶ 4,394:
end if
ip += 1
end while</
=={{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
<
நிரல்பாகம் fact ( n )
@( n == 0 ) ஆனால்
Line 2,541 ⟶ 4,422:
பதிப்பி fact ( 10 )
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
// ^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 ]</
<div style="width:full;overflow:scroll">
> factorial 8;;
Line 2,559 ⟶ 4,440:
=={{header|Factor}}==
{{trans|Haskell}}
<
: factorial ( n -- n ) [1,b] product ;</
The ''[1,b]'' word takes a number from the stack and pushes a range, which is then passed to ''product''.
=={{header|FALSE}}==
<
^'0- f;!.</
Recursive:
<
=={{header|Fancy}}==
<
def factorial {
1 upto: self . product
Line 2,581 ⟶ 4,462:
1 upto: 10 do_each: |i| {
i to_s ++ "! = " ++ (i factorial) println
}</
=={{header|Fantom}}==
The following uses 'Ints' to hold the computed factorials, which limits results to a 64-bit signed integer.
<
{
static Int factorialRecursive (Int n)
Line 2,620 ⟶ 4,501:
echo (factorialFunctional(20))
}
}</
=={{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===
<
===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."
<
dup 33 u> -24 and throw
dup 2 < IF
Line 2,641 ⟶ 4,583:
-5 factorial d.
:2: Invalid numeric argument
</syntaxhighlight>
=={{header|Fortran}}==
===Fortran 90===
A simple one-liner is sufficient.
<
Recursive functions were added in Fortran 90, allowing the following:
<syntaxhighlight lang="fortran">INTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS)
INTEGER, INTENT(IN) :: X
IF (X <= 1) THEN
ANS = 1
ELSE
ANS = X * RECURSIVE_FACTORIAL(X-1)
END IF
END FUNCTION RECURSIVE_FACTORIAL</syntaxhighlight>
===FORTRAN 77===
<syntaxhighlight lang="fortran"> INTEGER FUNCTION MFACT(N)
INTEGER N,I,FACT
FACT=1
IF (N.EQ.0) GOTO 20
FACT=FACT*I
10 CONTINUE
20 CONTINUE
END</syntaxhighlight>
=={{header|friendly interactive shell}}==
Line 2,708 ⟶ 4,619:
===Iterative===
<
function factorial
set x $argv[1]
Line 2,717 ⟶ 4,628:
echo $result
end
</syntaxhighlight>
===Recursive===
<
function factorial
set x $argv[1]
Line 2,729 ⟶ 4,640:
end
end
</syntaxhighlight>
=={{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:
* Factorials are calculated once and cached in memory so further recalculation is fast.
* 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.
* When calculating a factorial within the caching limit, say, 5000!, all of the factorials smaller than this will get calculated and cached in memory.
* 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?)
* 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]]
</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 ===
<
if n < 0
error( 'factorial: n should be non-negative' )
Line 2,752 ⟶ 4,689:
res *= i
res</
=== Recursive ===
<
factorial( (0|1) ) = 1
factorial( n )
| n > 0 = n*factorial( n - 1 )
| otherwise = error( 'factorial: n should be non-negative' )</
=== Tail-recursive ===
<
| n >= 0 =
def
Line 2,769 ⟶ 4,706:
fact( 1, n )
| otherwise = error( 'factorial: n should be non-negative' )</
=== Using a library function ===
<
| n >= 0 = product( 1..n )
| otherwise = error( 'factorial: n should be non-negative' )</
=={{header|Futhark}}==
Line 2,781 ⟶ 4,718:
=== Recursive ===
<syntaxhighlight lang="futhark">
fun fact(n: int): int =
if n == 0 then 1
else n * fact(n-1)
</syntaxhighlight>
== Iterative ==
<syntaxhighlight lang="futhark">
fun fact(n: int): int =
loop (out = 1) = for i < n do
out * (i+1)
in out
</syntaxhighlight>
=={{header|FutureBasic}}==
<
window 1, @"Factorial", ( 0, 0, 300, 550 )
local fn factorialIterative( n as long ) as double
if ( n > 1 )
f = 1
for i = 2
f = f * i
else
f = 1
end if
end fn = f
local fn factorialRecursive( n as long ) as double
if ( n < 2 )
else
end if
end fn = f
for i = 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Iterative: 0 = 1
Line 2,874 ⟶ 4,813:
</pre>
=={{header|GAP}}==
<
Factorial(5);
# An implementation
fact := n -> Product([1 .. n]);</
=={{header|Genyris}}==
<
if (< n 2) 1
* n
factorial (- n 1)</
=={{header|GML}}==
<
j = 1
for(i = 1; i <= n; i += 1)
j *= i
return j</
=={{header|gnuplot}}==
Gnuplot has a builtin <code>!</code> factorial operator for use on integers.
<
set key left
plot int(x)!</
If you wanted to write your own it can be done recursively.
<
# calculated on int(n) in that case.
# Arranging the condition as "n>=2" avoids infinite recursion if
Line 2,961 ⟶ 4,852:
set xrange [0:4.95]
set key left
plot factorial(x)</
=={{header|Go}}==
===Iterative===
Sequential, but at least handling big numbers:
<
import (
Line 2,987 ⟶ 4,878:
}
return r
}</
===Built in, exact===
Built in function currently uses a simple divide and conquer technique. It's a step up from sequential multiplication.
<
import (
Line 3,004 ⟶ 4,895:
func main() {
fmt.Println(factorial(800))
}</
===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===
<
import (
Line 3,024 ⟶ 4,915:
}
fmt.Println(100, factorial(100))
}</
{{out}}
<pre>
Line 3,041 ⟶ 4,932:
</pre>
===Built in, Lgamma===
<
import (
Line 3,066 ⟶ 4,957:
fmt.Println(100, factorial(100))
fmt.Println(800, factorial(800))
}</
{{out}}
<pre>
Line 3,086 ⟶ 4,977:
=={{header|Golfscript}}==
'''Iterative''' (uses folding)
<
5fact puts # test</
or
<
'''Recursive'''
<
=={{header|
<
#FACTORIAL.
Line 3,110 ⟶ 5,001:
(11,7):GOTO 0
(13,3):PRINT
</syntaxhighlight>
=={{header|Groovy}}==
=== Recursive ===
A recursive closure must be ''pre-declared''.
<
rFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger }</
=== Iterative ===
<
Test Program:
<
def start = System.currentTimeMillis()
def result = c()
Line 3,137 ⟶ 5,029:
factList.each { printf ' %3d', it }
println()
}</
{{out}}
Line 3,144 ⟶ 5,036:
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:
<
Or, using composition and omitting the argument ([https://www.haskell.org/haskellwiki/Partial_application partial application]):
<
Or, written explicitly as a fold:
<
''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:
<
Or, written without library functions:
<
factorial 0 = 1
factorial n = n * factorial (n-1)</
Tail-recursive, checking the negative case:
<
| n >= 0 = go 1 n
| otherwise = error "Negative factorial!"
where go acc 0 = acc
go acc n = go (acc * n) (n - 1)</
Using postfix notation:
<
(!) :: Integer -> Integer
(!) 0 = 1
(!) n = n * (
main :: IO ()
main = do
print (5 !)
print ((4 !) !)</
=== 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===
<
let acc 1
while n > 0
Line 3,187 ⟶ 5,213:
endwhile
return acc
endfun</
===Recursive===
<
if n <= 0
return 1
Line 3,195 ⟶ 5,221:
return n * fac (n - 1)
endif
endfun</
=={{header|HicEst}}==
<
FUNCTION factorial(n)
Line 3,205 ⟶ 5,231:
factorial = factorial * i
ENDDO
END</
=={{header|HolyC}}==
=== Iterative ===
<
U64 i, result = 1;
for (i = 1; i <= n; ++i)
Line 3,217 ⟶ 5,243:
Print("1: %d\n", Factorial(1));
Print("10: %d\n", Factorial(10));</
Note: Does not support negative numbers.
=== Recursive ===
<
if (n == 0)
return 1;
Line 3,232 ⟶ 5,258:
Print("+1: %d\n", Factorial(1));
Print("+10: %d\n", Factorial(10));
Print("-10: %d\n", Factorial(-10));</
=={{header|Hy}}==
<
(reduce *
(range 1 (inc n))
Line 3,241 ⟶ 5,267:
(print (! 6)) ; 720
(print (! 0)) ; 1</
=={{header|i}}==
<
return n!
}
Line 3,256 ⟶ 5,282:
print(factorial(22))
}
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
===Recursive===
<
n := integer(n) | runerr(101, n)
if n < 0 then fail
return if n = 0 then 1 else n*factorial(n-1)
end </
===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':
<
local i
n := integer(n) | runerr(101, n)
Line 3,274 ⟶ 5,300:
every i *:= 1 to n
return i
end</
=={{header|IDL}}==
<
return, product(lindgen(n)+1)
end</
=={{header|Inform 6}}==
<
if (n == 0)
return 1;
else
return n * factorial(n - 1);
];</
=={{header|Insitux}}==
{{trans|Clojure}}
'''Iterative'''
<syntaxhighlight lang="insitux">
(function factorial n
(... *1 (range 2 (inc n))))
</syntaxhighlight>
'''Recursive'''
<syntaxhighlight lang="insitux">
(function factorial x
(if (< x 2)
1
(*1 x (factorial (dec x)))))
</syntaxhighlight>
=={{header|Io}}==
Factorials are built-in to Io:
<syntaxhighlight lang
=={{header|J}}==
=== Operator ===
<
40320</
=== Iterative / Functional ===
<
40320</
=== Recursive ===
<
40320</
=== 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">
<
40320 0.931384 4.59084
! 800x NB. Also arbitrarily large
7710530113353860041446393977750283605955564018160102391634109940339708518270930693670907697955390330926478612242306774446597851526397454014801846531749097625044706382742591201733097017026108750929188168469858421505936237186038616420630788341172340985137252...</
</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===
<
package programas;
Line 3,370 ⟶ 5,483:
}
</syntaxhighlight>
===Recursive===
<
package programas;
Line 3,431 ⟶ 5,544:
}
</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 3,437 ⟶ 5,591:
===Iterative===
<
//check our edge case
if (n < 0) { throw "Number must be non-negative"; }
var
//we skip zero and one since both are 1 and are identity
while (n > 1) {
n--;
}
return
}</
===Recursive===
Line 3,454 ⟶ 5,608:
====ES5 (memoized )====
<
var memo = {};
Line 3,464 ⟶ 5,618:
return factorial(x);
})(18);</
{{Out}}
<syntaxhighlight lang
Or, assuming that we have some sort of integer range function, we can memoize using the accumulator of a fold/reduce:
<
'use strict';
Line 3,498 ⟶ 5,652:
return factorial(18);
})();</
{{Out}}
<syntaxhighlight lang
====ES6====
<
Or, as an alternative to recursion, we can fold/reduce a product function over the range of integers 1..n
<
'use strict';
Line 3,537 ⟶ 5,691:
// MAIN ------
return test();
})();</
{{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}}==
<
BEGIN
ITEM ARG U;
Line 3,550 ⟶ 5,759:
TEMP = TEMP*I;
FACTORIAL = TEMP;
END</
=={{header|Joy}}==
<<syntaxhighlight lang
6!.
</syntaxhighlight>
=={{header|jq}}==
An efficient and idiomatic definition in jq is simply to multiply the first n integers:<
reduce range(1; .+1) as $i (1; . * $i);</
Here is a rendition in jq of the standard recursive definition of the factorial function, assuming n is non-negative: <
if n <= 1 then n
else n * fact(n-1)
end;
</
def _fact:
# Input: [accumulator, counter]
Line 3,569 ⟶ 5,780:
end;
# Extract the accumulated value from the output of _fact:
[1, .] | _fact | .[0] ;</
=={{header|Jsish}}==
<
/* recursive */
Line 3,593 ⟶ 5,804:
;factorial(42);
try { factorial(-1); } catch (err) { puts(err); }
}</
{{out}}
Line 3,631 ⟶ 5,842:
'''Dynamic version''':
<
n < 0 && return zero(n)
f = one(n)
Line 3,642 ⟶ 5,853:
for i in 10:20
println("$i -> ", fact(i))
end</
{{out}}
Line 3,658 ⟶ 5,869:
'''Alternative version''':
<
@show fact2(20)</
{{out}}
<pre>fact2(20) = 2432902008176640000</pre>
Line 3,665 ⟶ 5,876:
=={{header|K}}==
===Iterative===
<
facti 5
120</
===Recursive===
<
factr 6
720</
=={{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">
factRecursive::{:[x>1;x*.f(x-1);1]}
factIterative::{*/1+!x}
</syntaxhighlight>
=={{header|KonsolScript}}==
<
Var:Number ret;
if (n >= 0) {
Line 3,693 ⟶ 5,948:
}
return ret;
}</
=={{header|Kotlin}}==
<
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
Line 3,715 ⟶ 5,970:
println("$n! = " + facti(n))
println("$n! = " + factr(n))
}</
{{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===
<
5 fact
120
</syntaxhighlight>
===Recursive===
<
: fact dup 2 < if else dup 1 - fact * then ;
5 fact
120
</syntaxhighlight>
=={{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 * fn((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===
<
local(x = 1)
with i in generateSeries(2, #n)
Line 3,743 ⟶ 6,094:
}
return #x
}</
===Recursive===
<
=={{header|Latitude}}==
===Functional===
<
1 upto ($1 + 1) product.
}.</
===Recursive===
<
takes '[n].
if { n == 0. } then {
Line 3,763 ⟶ 6,114:
n * factorial (n - 1).
}.
}.</
===Iterative===
<
local 'acc = 1.
1 upto ($1 + 1) do {
Line 3,772 ⟶ 6,123:
}.
acc.
}.</
=={{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 3,781 ⟶ 6,170:
''Using the'' <tt>cond</tt> ''form'':
<
(defun factorial (n)
(cond
((== n 0) 1)
((> n 0) (* n (factorial (- n 1))))))
</syntaxhighlight>
''Using guards (with the'' <tt>when</tt> ''form)'':
<
(defun factorial
((n) (when (== n 0)) 1)
((n) (when (> n 0))
(* n (factorial (- n 1)))))
</syntaxhighlight>
''Using pattern matching and a guard'':
<
(defun factorial
((0) 1)
((n) (when (> n 0))
(* n (factorial (- n 1)))))
</syntaxhighlight>
===Tail-Recursive Version===
<
(defun factorial (n)
(factorial n 1))
Line 3,814 ⟶ 6,203:
((n acc) (when (> n 0))
(factorial (- n 1) (* n acc))))
</syntaxhighlight>
Example usage in the REPL:
<
> (lists:map #'factorial/1 (lists:seq 10 20))
(3628800
Line 3,830 ⟶ 6,219:
121645100408832000
2432902008176640000)
</syntaxhighlight>
Or, using <tt>io:format</tt> to print results to <tt>stdout</tt>:
<
> (lists:foreach
(lambda (x)
Line 3,850 ⟶ 6,239:
2432902008176640000
ok
</syntaxhighlight>
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|Lingo}}==
===Recursive===
<
if n<=1 then return 1
return n * fact(n-1)
end</
===Iterative===
<
res = 1
repeat with i = 2 to n
Line 3,899 ⟶ 6,257:
end repeat
return res
end</
=={{header|Lisaac}}==
<
+ result : INTEGER;
(x <= 1).if {
Line 3,910 ⟶ 6,268:
};
result
);</
=={{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}}==
<
function factorialr n
if n < 2 then
Line 3,937 ⟶ 6,338:
// iterative
function factorialit n
if n > 1 then
repeat with i = 1 to n
Line 3,944 ⟶ 6,345:
end if
return f
end factorialit</
=={{header|LLVM}}==
<
; source_filename = "factorial.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 4,026 ⟶ 6,427:
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</
{{out}}
<pre>120</pre>
Line 4,033 ⟶ 6,434:
===Recursive===
<
if :n < 2 [output 1]
output :n * factorial :n-1
end</
===Iterative===
Line 4,042 ⟶ 6,443:
NOTE: Slight code modifications may needed in order to run this as each Logo implementation differs in various ways.
<
make "fact 1
make "i 1
repeat :n [make "fact :fact * :i make "i :i + 1]
print :fact
end</
=={{header|LOLCODE}}==
<
HOW IZ I Faktorial YR Number
Line 4,065 ⟶ 6,466:
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR Loop
KTHXBYE</
{{Out}}
<pre>0! = 1
Line 4,083 ⟶ 6,484:
=={{header|Lua}}==
===Recursive===
<
return n > 0 and n * fact(n-1) or 1
end</
===Tail Recursive===
<
acc = acc or 1
if n == 0 then
Line 4,093 ⟶ 6,494:
end
return fact(n-1, n*acc)
end</
===Memoization===
The memoization table can be accessed directly (eg. <code>fact[10]</code>) and will return the memoized value,
Line 4,099 ⟶ 6,500:
If called as a function (eg. <code>fact(10)</code>), the value will be calculated, memoized and returned.
<
__call = function(t,n)
if n < 0 then return 0 end
Line 4,105 ⟶ 6,506:
return t[n]
end
})</
=={{header|M2000 Interpreter}}==
Line 4,117 ⟶ 6,517:
1@ is 1 in Decimal type (27 digits).
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Locale 1033 ' ensure #,### print with comma
Line 4,140 ⟶ 6,540:
}
Checkit
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 4,173 ⟶ 6,573:
=={{header|M4}}==
<
dnl
factorial(5)</
{{out}}
Line 4,181 ⟶ 6,581:
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 “cascading” 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">
> 5!;
120
</syntaxhighlight>
Recursive
<
if n = 0 or n = 1 then
1
Line 4,196 ⟶ 6,680:
end if
end proc:
</syntaxhighlight>
<syntaxhighlight 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>
Iterative
<syntaxhighlight lang="maple">
IterFact := proc( n :: nonnegint )
local i;
mul( i, i = 2 .. n )
end proc:
</syntaxhighlight>
<syntaxhighlight 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>
=={{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 ===
<
factorial[0] = 1</
=== Iterative (direct loop) ===
<
Block[{i, result = 1}, For[i = 1, i <= n, ++i, result *= i]; result]</
=== Iterative (list) ===
<
=={{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.
<
=== Recursive ===
<
if n==0
f=1;
Line 4,239 ⟶ 6,723:
else
f=n*fac(n-1);
end</
=== Iterative ===
A possible iterative solution:
<
b=1;
for i=1:a
b=b*i;
end</
=={{header|Maude}}==
<syntaxhighlight lang="maude">
fmod FACTORIAL is
Line 4,265 ⟶ 6,749:
red 11 ! .
</syntaxhighlight>
=={{header|Maxima}}==
=== Built-in ===
<syntaxhighlight lang
=== Recursive ===
<
=== Iterative===
<
=={{header|MAXScript}}==
=== Iterative ===
<
(
if n == 0 then return 1
Line 4,286 ⟶ 6,770:
)
fac
)</
=== Recursive ===
<
(
local fac = 1
Line 4,296 ⟶ 6,780:
)
fac
)</
=={{header|Mercury}}==
=== Recursive (using arbitrary large integers and memoisation) ===
<
:- interface.
Line 4,315 ⟶ 6,799:
-> integer(1)
; factorial(N - integer(1)) * N
).</
A small test program:
<
:- interface.
:- import_module io.
Line 4,335 ⟶ 6,819:
Result = factorial(Number),
Fmt = integer.to_string,
io.format("factorial(%s) = %s\n", [s(Fmt(Number)), s(Fmt(Result))], !IO).</
Example output:
<
=={{header|
{{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 ===
<
##################################
# Factorial; iterative #
Line 4,406 ⟶ 6,914:
li $v0, 10 #set syscall arg to EXIT
syscall #make the syscall
</syntaxhighlight>
=== Recursive ===
<
#reference code
#int factorialRec(int n){
Line 4,451 ⟶ 6,959:
mul $v0, $a0, $v0
jr $ra
</syntaxhighlight>
=={{header|Mirah}}==
<
2.upto(n-1) do |i|
n *= i
Line 4,461 ⟶ 6,969:
end
puts factorial_iterative 10</
=={{header|МК-61/52}}==
Line 4,470 ⟶ 6,978:
=={{header|ML/I}}==
===Iterative===
<
"" Factorial - iterative
MCSKIP MT,<>
Line 4,486 ⟶ 6,994:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</
===Recursive===
<
"" Factorial - recursive
MCSKIP MT,<>
Line 4,500 ⟶ 7,008:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 4,528 ⟶ 7,036:
ReadChar
END Factorial.</
=={{header|Modula-3}}==
===Iterative===
<
VAR
result := n;
Line 4,542 ⟶ 7,050:
END;
RETURN result;
END FactIter;</
===Recursive===
<
VAR result := 1;
Line 4,552 ⟶ 7,060:
END;
RETURN result;
END FactRec;</
=={{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===
<
If num<0 Quit "Negative number"
If num["." Quit "Not an integer"
Line 4,568 ⟶ 7,088:
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative number
Write $$factorial(3.7) ; Not an integer</
===Recursive===
<
If num<0 Quit "Negative number"
If num["." Quit "Not an integer"
Line 4,582 ⟶ 7,102:
Write $$factorial(3) ; 6
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative
Write $$factorial(3.7) ; Not an integer</
=={{header|MyrtleScript}}==
<
int factorial = a
repeat int i = (a - 1) : i == 0 : i-- {
Line 4,592 ⟶ 7,112:
}
return factorial
}</
=={{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}}==
<
var i = 1;
var result = 1;
Line 4,607 ⟶ 7,137:
};
$print(factorial(10));</
=={{header|Nemerle}}==
Line 4,613 ⟶ 7,143:
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.
<
using System.Console;
Line 4,647 ⟶ 7,177:
accumulator //implicit return
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 4,700 ⟶ 7,230:
fact = 1
return fact</
{{out}}
<pre>
Line 4,710 ⟶ 7,240:
=={{header|newLISP}}==
<
(lambda (n) (exp (gammaln (+ n 1))))
> (factorial 4)
24</
=={{header|Nial}}==
(from Nial help file)
<
Using it
<
=24</
=={{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===
<
import math
let i:int = fac(x)
</syntaxhighlight>
===Recursive===
<
if x > 0: x * factorial(x - 1)
else: 1</
===Iterative===
<
result = 1
for i in 2..x:
result *= i</
=={{header|Niue}}==
===Recursive===
<
( test )
4 factorial . ( => 24 )
10 factorial . ( => 3628800 )</
=={{header|
<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">
MODULE Factorial;
IMPORT
Line 4,789 ⟶ 7,377:
END
END Factorial.
</syntaxhighlight>
{{Out}}
<pre>
Line 4,813 ⟶ 7,401:
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===
<
class Fact {
function : Main(args : String[]) ~ Nil {
Line 4,823 ⟶ 7,481:
}
}
}</
=={{header|OCaml}}==
===Recursive===
<
if n <= 0 then 1
else n * factorial (n-1)</
The following is tail-recursive, so it is effectively iterative:
<
let rec loop i accum =
if i > n then accum
else loop (i + 1) (accum * i)
in loop 1 1</
===Iterative===
It can be done using explicit state, but this is usually discouraged in a functional language:
<
let result = ref 1 in
for i = 1 to n do
result := !result * i
done;
!result</
===Bignums===
Line 4,850 ⟶ 7,508:
The following code uses the Zarith package to calculate the factorials of larger numbers:
<
let rec loop acc = function
| 0 -> acc
Line 4,861 ⟶ 7,519:
Sys.argv.(1) |> int_of_string |> factorial |> Z.print;
print_newline ()
end</
{{out}}
Line 4,869 ⟶ 7,527:
=={{header|Octave}}==
<
printf("%d\n", factorial(50));
Line 4,891 ⟶ 7,549:
endfunction
printf("%d\n", iter_fact(50));</
{{out}}
Line 4,905 ⟶ 7,563:
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 :
<
Imperative :
<
{{out}}
Line 4,923 ⟶ 7,598:
=={{header|Order}}==
Simple recursion:
<
#define ORDER_PP_DEF_8fac \
Line 4,931 ⟶ 7,606:
8mul(8N, 8fac(8dec(8N))))))
ORDER_PP(8to_lit(8fac(8))) // 40320</
Tail recursion:
<
#define ORDER_PP_DEF_8fac \
Line 4,943 ⟶ 7,618:
8apply(8F, 8seq_to_tuple(8seq(1, 1, 8F))))))
ORDER_PP(8to_lit(8fac(8))) // 40320</
=={{header|Oz}}==
=== Folding ===
<
{FoldL {List.number 1 N 1} Number.'*' 1}
end</
=== Tail recursive ===
<
fun {Loop N Acc}
if N < 1 then Acc
Line 4,960 ⟶ 7,635:
in
{Loop N 1}
end</
=== Iterative ===
<
Result = {NewCell 1}
in
Line 4,969 ⟶ 7,644:
end
@Result
end</
=={{header|Panda}}==
<syntaxhighlight lang="panda">fun fac(n) type integer->integer
product{{1..n}}
1..10.fac
</syntaxhighlight>
=={{header|PARI/GP}}==
Line 4,975 ⟶ 7,657:
===Recursive===
<
===Iterative===
This is an improvement on the naive recursion above, being faster and not limited by stack space.
<
===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.
<
===Recursive 1===
Even faster
<
my(c);
if( b == a, return(a));
Line 4,997 ⟶ 7,679:
}
fact(n) = f(1, n)</
===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.
<
===Gamma===
Note also the presence of <code>factorial</code> and <code>lngamma</code>.
<
===Moessner's algorithm===
Line 5,011 ⟶ 7,693:
: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.
<
my(v=vector(n+1,i,i==1));
for(i=2,n+1,
Line 5,019 ⟶ 7,701:
);
v[n+1]
};</
=={{header|Pascal}}==
=== Iterative ===
<
var
i, result: integer;
Line 5,038 ⟶ 7,713:
result := result * i;
factorial := result
end;</
=== 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 ===
<
begin
if n = 0
Line 5,047 ⟶ 7,855:
else
factorial := n*factorial(n-1)
end;</
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function FactIter(n: integer): BigInteger;
begin
Result := 1;
for var i:=2 to n do
Result *= i;
end;
function FactRec(n: integer): BigInteger;
begin
if n = 0 then
Result := 1
else Result := n * FactRec(n - 1);
end;
begin
for var i:=1 to 20 do
Println(i,FactRec(i),FactIter(i));
end.
</syntaxhighlight>
{{out}}
<pre>
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|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
However, just to prove that it can be done, here's one possible implementation:
<
<@ SAYFATLIT>123</@></
=={{header|Perl}}==
=== Iterative ===
<
{
my $n = shift;
Line 5,074 ⟶ 7,953:
$r *= $_ for 1..shift;
$r;
}</
=== Recursive ===
<
{
my $n = shift;
($n == 0)? 1 : $n*factorial($n-1);
}</
=== Functional ===
<
sub factorial
{
my $n = shift;
reduce { $a * $b } 1, 1 .. $n
}</
=== Modules ===
Each of these will print 35660, the number of digits in 10,000!.
{{libheader|ntheory}}
<
# factorial returns a UV (native unsigned int) or Math::BigInt depending on size
say length( factorial(10000) );</
<
say length( 10000->bfac );</
<
say length( Math::GMP->new(10000)->bfac );</
<
say length( ifact(10000) );</
=={{header|
<syntaxhighlight lang="peylang">
-- calculate factorial
chiz a = 5;
chiz n = 1;
ta a >= 2
{
n *= a;
a -= 1;
}
chaap n;
</syntaxhighlight>
=={{header|Phix}}==
{{libheader|Phix/basics}}
standard iterative factorial builtin, reproduced below. returns inf for 171 and above, and is not accurate above 22 on 32-bit, or 25 on 64-bit.
<!--<syntaxhighlight lang="phix">-->
<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>
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<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>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<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 ===
<
function factorial($n) {
if ($n < 0) {
Line 5,142 ⟶ 8,111:
return $factorial;
}
?></
=== Recursive ===
<
function factorial($n) {
if ($n < 0) {
Line 5,158 ⟶ 8,127:
}
}
?></
=== One-Liner ===
<
function factorial($n) { return $n == 0 ? 1 : array_product(range(1, $n)); }
?></
=== Library ===
Requires the GMP library to be compiled in:
<syntaxhighlight lang
=={{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}}==
<
(if (=0 N)
1
(* N (fact (dec N))) ) )</
or:
<
(apply * (range 1 N) ) )</
which only works for 1 and bigger.
Line 5,185 ⟶ 8,159:
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
<
not
in(number)
Line 5,221 ⟶ 8,195:
pop // continues from pointer 2
out(number)
exit</
=={{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}}==
<
declare N fixed binary nonassignable;
declare i fixed decimal (10);
Line 5,235 ⟶ 8,264:
end;
return (F);
end factorial;</
=={{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===
<
dup 0 eq % check for the argument being 0
{
Line 5,250 ⟶ 8,426:
mul % multiply the result with n
} ifelse
} def</
===Iterative===
<
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</
===Combinator===
{{libheader|initlib}}
<
=={{header|PowerShell}}==
===Recursive===
<
if ($x -eq 0) {
return 1
}
return $x * (Get-Factorial ($x - 1))
}</
===Iterative===
<
if ($x -eq 0) {
return 1
Line 5,297 ⟶ 8,455:
return $product
}
}</
===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.
<
if ($x -eq 0) {
return 1
}
return (Invoke-Expression (1..$x -join '*'))
}</
=={{header|Processing}}==
===Recursive===
<syntaxhighlight lang="processing">
int fact(int n){
if(n <= 1){
Line 5,317 ⟶ 8,476:
}
}
</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>
Line 5,327 ⟶ 8,510:
{{works with|SWI Prolog}}
===Recursive===
<
fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*X.</
===Tail recursive===
<
fact(1, N, 1, NF).
Line 5,337 ⟶ 8,520:
X1 is X + 1,
FX1 is FX * X1,
fact(X1, N, FX1, F).</
===Fold===
We can simulate foldl.
<
%
foldl(_Pred, Val, [], Val).
Line 5,353 ⟶ 8,536:
fact(X, F) :-
numlist(2, X, L),
foldl(p, 1, L, F).</
===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 :
<
% foldl(Pred, Init, List, R).
Line 5,367 ⟶ 8,550:
fact(N, F) :-
numlist(2, N, L),
foldl(\X^Y^Z^(Z is X * Y), 1, L, F).</
===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.
<
fact(N, FN) :-
Line 5,383 ⟶ 8,566:
cont_fact(N1, FT, P),
call(Pred, FT, F)
).</
=={{header|Pure}}==
===Recursive===
<
= 1 otherwise;
let facts = map fact (1..10); facts;</
===Tail Recursive===
<
loop p n = if n>0 then loop (p*n) (n-1) else p;
end;</
=={{header|Python}}==
===Library===
{{works with|Python|2.6+, 3.x}}
<
math.factorial(n)</
===Iterative===
<
result = 1
for i in range(1, n+1):
result *= i
return result</
===Functional===
<
from functools import reduce
def factorial(n):
return reduce(mul, range(1,n+1), 1)</
or
<
from operator import mul
Line 5,439 ⟶ 8,604:
return list(
accumulate(chain([1], range(1, 1 + n)), mul)
)[-1]</
or including the sequence that got us there:
<
from operator import mul
Line 5,454 ⟶ 8,619:
print(factorials(5))
# -> [1, 1, 2, 6, 24, 120]</
or
<syntaxhighlight lang="python">from numpy import prod
def factorial(n):
return prod(range(1, n + 1), dtype=int)</syntaxhighlight>
===Recursive===
<
z=1
if n>1:
z=n*factorial(n-1)
return z</
{{out}}
Line 5,474 ⟶ 8,645:
5 120
>>></pre>
or
<syntaxhighlight lang="python">def factorial(n):
return n * factorial(n - 1) if n else 1</syntaxhighlight>
===Numerical Approximation===
Line 5,479 ⟶ 8,654:
The gamma function Γ(x) extends the domain of the factorial function, while maintaining the relationship that factorial(x) = Γ(x+1).
<
# Coefficients used by the GNU Scientific Library
Line 5,505 ⟶ 8,680:
print "factorial(-0.5)**2=",factorial(-0.5)**2
for i in range(10):
print "factorial(%d)=%s"%(i,factorial(i))</
{{out}}
<pre>
Line 5,524 ⟶ 8,699:
===Iterative===
====Point-free====
<syntaxhighlight lang
or
<syntaxhighlight lang
or
<syntaxhighlight lang
====As a function====
<
===Recursive===
<
=={{header|
===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 ===
<
if (
else n *
}</
===Iterative===
<
f = 1
for (i in 2:n) f <- f * i
}
f
}</
===Numerical Approximation===
R has a native gamma function and a wrapper for that function that can produce factorials. E.g.
<
=={{header|Racket}}==
=== Recursive ===
The standard recursive style:
<
(if (= 0 n)
1
(* n (factorial (- n 1)))))</
However, it is inefficient. It's more efficient to use an accumulator.
<
(define (fact n acc)
(if (= 0 n)
acc
(fact (- n 1) (* n acc))))
(fact n 1))</
=== 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 ===
<
f := 1
для i от 1 до n
Line 5,633 ⟶ 8,835:
кц
Возврат f
Кон Фун</
=== Recursive ===
<
Если n = 1
Возврат 1
Line 5,648 ⟶ 8,850:
печать 'n! = '
печать Факт(n)
Кон проц </
=== 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:
<
result = 1;
for(i <- [1..n])
result *= i;
return result;
}</
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:
<
{{out}}
<pre>rascal>factorial_iter(10)
Line 5,670 ⟶ 8,881:
===Recursive===
<
if(n>1) return n*factorial_rec(n-1);
else return 1;
}</
{{out}}
<pre>rascal>factorial_rec(10)
int: 3628800</pre>
=={{header|RASEL}}==
<syntaxhighlight lang="text">1&$:?v:1-3\$/1\
>$11\/.@</syntaxhighlight>
=={{header|REBOL}}==
<
Title: "Factorial"
URL: http://rosettacode.org/wiki/Factorial_function
Line 5,733 ⟶ 8,948:
; Test them on numbers zero to ten.
for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]]</
{{out}}
<pre>0 : 1 1 1
Line 5,747 ⟶ 8,962:
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.
<
: factorial dup 0 = [ 1+ ] [ <factorial> ] if ;</
=={{header|REXX}}==
Line 5,758 ⟶ 9,026:
<br><br> <big> 25,000'''!''' </big> is exactly <big> 99,094 </big> decimal digits.
<br><br>Most REXX interpreters can handle eight million decimal digits.
<
numeric digits 100000 /*100k digits: handles N up to 25k.*/
parse arg n /*obtain optional argument from the CL.*/
Line 5,766 ⟶ 9,034:
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
!=
do j=2 to n; !=!*j /*compute the factorial the hard way. */
end /*j*/ /* [↑] where da rubber meets da road. */
Line 5,772 ⟶ 9,040:
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say ! /*display the factorial
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error***'; say; say arg(1); say; exit 13</
<pre>
100! is [158 digits]:
Line 5,786 ⟶ 9,054:
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>
<
/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/
numeric digits 99 /*99 digits initially, then expanded. */
Line 5,823 ⟶ 9,091:
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
!=
do j=2 to n; !=!*j
if pos(.,!)==0 then iterate
parse var ! 'E' digs
end /*j*/
!= !/1 /*normalize the factorial product. */
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say !
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; exit 13</
<pre>
1000! is [2568 digits]:
Line 5,854 ⟶ 9,122:
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
<br>is a multiple of five [or some other method], strip the trailing zeroes, and then convert it back to binary
<br>wouldn't be necessary to convert to/from base ten for checking for trailing zeros (in decimal).
<
numeric digits 200 /*start with two hundred digits. */
parse arg N .
if N=='' | N=="," then N= 0 /*Not specified? Then use the default.*/
!=
do j=2 to N /*compute factorial the hard way. */
old!=
!= ! *
if pos(.,!) \==0 then do /*is the ! in exponential notation?*/
d= digits()
numeric digits d+d%10 /*add 10% to the decimal digits. */
!= old! * j
end /*IFF ≡ if and only if. [↓] */
parse var ! '' -1
if _==0 then != strip(!, , 0)
end /*j*/ /* [↑] ... right-most digit is zero. */
z=
do v=5 by 0 while v<=N /*calculate number of trailing zeroes. */
z= z
v= v *
end /*v*/ /* [↑] we only advance V by ourself.*/
/*stick a fork in it, we're all done. */
!= ! || copies(0, z)
if z==0 then z= 'no'
say N'! is ['length(!) " digits with " z ' trailing zeroes]:'
say /*display blank line (for whitespace).*/
say ! /*display the factorial product. */</syntaxhighlight>
<!-- The word ''gooder'' is a humorous use of the non-word. -->
<pre>
100! is [158 digits with 24 trailing zeroes]:
Line 5,892 ⟶ 9,159:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
</pre>
(Output is shown at <big> '''<sup>4</sup>/<sub>5</sub>''' </big> size.)
Line 5,956 ⟶ 9,223:
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}}==
<
give n
x = fact(n)
Line 5,964 ⟶ 9,265:
func fact nr if nr = 1 return 1 else return nr * fact(nr-1) ok
</syntaxhighlight>
=={{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
Line 5,976 ⟶ 9,297:
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.
Line 5,989 ⟶ 9,310:
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 5,996 ⟶ 9,340:
* [[MRI]] does not optimize tail recursion. So factorial_tail_recursive(10000) might also fail.
<
def factorial_recursive(n)
n.zero? ? 1 : n * factorial_recursive(n - 1)
Line 6,034 ⟶ 9,378:
b.report('inject:') {m.times {factorial_inject(n)}}
b.report('reduce:') {m.times {factorial_reduce(n)}}
end</
The benchmark depends on the Ruby implementation.
With [[MRI]], <code>#factorial_reduce</code> seems slightly faster than others.
Line 6,046 ⟶ 9,390:
inject: 2.500000 0.130000 2.630000 ( 2.641898)
reduce: 2.110000 0.230000 2.340000 ( 2.338166)</pre>
=={{header|Rust}}==
<
match n {
0 => 1,
Line 6,077 ⟶ 9,400:
fn factorial_iterative(n: u64) -> u64 {
(1..=n
}
Line 6,088 ⟶ 9,411:
}
}
</syntaxhighlight>
=={{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}}==
<
-- recursive
Line 6,119 ⟶ 9,442:
#OUT + fact(a) + " = " + fact_iter(a) + "\n";
end;
end;</
=={{header|S-BASIC}}==
S-BASIC's double-precision real data type supports up to 14 digits,
thereby allowing calculation up to 15! without loss of precision
<syntaxhighlight lang="BASIC">
function factorial(n=real.double)=real.double
if n = 0 then n = 1 else n = n * factorial(n-1)
end = n
var i=integer
print "Factorial Calculator"
print " n n!"
print "----------------------"
for i=1 to 15
print using "## #,###,###,###,###";i;factorial(i)
next i
end
</syntaxhighlight>
An iterative rather than recursive approach works equally well, if that
is your preference.
<syntaxhighlight lang="BASIC">
function factorial(n=real.double)=real.double
var i, f = real.double
f = 1
for i = 1 to n
f = f * i
next i
end = f
</syntaxhighlight>
{{out}}
<pre>
Factorial Calculator
n n!
----------------------
1 1
2 2
3 3
4 24
5 120
6 720
7 5,040
8 40,320
9 362,880
10 3,628,800
11 39,916,800
12 479,001,600
13 6,227,020,800
14 87,178,291,200
15 1,307,674,368,000
</pre>
=={{header|Scala}}==
Line 6,125 ⟶ 9,500:
===Imperative===
An imperative style using a mutable variable:
<syntaxhighlight lang
def factorial(n: Int) = {
var res = 1
for (i <- 1 to n)
res *= i
res
}
</syntaxhighlight>
===Recursive===
Using naive recursion:
<syntaxhighlight lang="scala">
def
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:
<
def factorial(n: Int) = (2 to n).product
</syntaxhighlight>
===Folding===
Using folding:
<syntaxhighlight lang
def factorial(n: Int) =
(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))(_ * _)
}
</syntaxhighlight>
{{out | Example used in the REPL}}
Line 6,174 ⟶ 9,559:
=={{header|Scheme}}==
===Recursive===
<syntaxhighlight lang
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))
</syntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<syntaxhighlight lang
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))
</syntaxhighlight>
===Iterative===
<syntaxhighlight lang
(define (factorial n)
(do ((i 1 (+ i 1))
(accum 1 (* accum i)))
((> i n) accum)))
</syntaxhighlight>
===Folding===
<syntaxhighlight lang="scheme">
;Using a generator and a function that apply generated values to a function taking two arguments
;A generator knows commands 'next? and 'next
Line 6,213 ⟶ 9,607:
(factorial 8)
;40320
</syntaxhighlight>
=={{header|Scilab}}==
Line 6,219 ⟶ 9,614:
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>.
<
===Iterative===
<syntaxhighlight lang="text">function f=factoriter(n)
f=1
for i=2:n
f=f*i
end
endfunction</
===Recursive===
<syntaxhighlight lang="text">function f=factorrec(n)
if n==0 then f=1
else f=n*factorrec(n-1)
end
endfunction</
===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</
=={{header|Seed7}}==
Line 6,251 ⟶ 9,646:
To avoid this limitations the functions below use [http://seed7.sourceforge.net/libraries/bigint.htm bigInteger]:
===Iterative===
<
result
var bigInteger: fact is 1_;
Line 6,260 ⟶ 9,655:
fact *:= i;
end for;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#iterative_fib]
===Recursive===
<
result
var bigInteger: fact is 1_;
Line 6,271 ⟶ 9,666:
fact := n * factorial(pred(n));
end if;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Line 6,277 ⟶ 9,672:
=={{header|Self}}==
Built in:
<syntaxhighlight lang
Iterative version:
<
</syntaxhighlight>
Recursive version:
<
Factorial is product of list of numbers from 1 to n.
(Vector indexes start at 0)
<
=={{header|SequenceL}}==
The simplest description: factorial is the product of the numbers from 1 to n:
<
Or, if you wanted to generate a list of all the factorials:
<
Or, written recursively:
<
factorial(n) :=
1 when n <= 0
else
n * factorial(n-1);</
Tail-recursive:
<
factorialHelper(1, n);
Line 6,308 ⟶ 9,703:
acc when n <= 0
else
factorialHelper(acc * n, n-1);</
=={{header|SETL}}==
<
proc fact(n);
if (n < 2) then
Line 6,328 ⟶ 9,722:
end loop;
return v;
end proc;</
=={{header|Shen}}==
<
0 -> 1
X -> (* X (factorial (- X 1))))</
=={{header|Sidef}}==
Recursive:
<
n == 0 ? 1 : (n * __FUNC__(n-1))
}</
Catamorphism:
<
1..n -> reduce({|a,b| a * b }, 1)
}</
Iterative:
<
var f = 1
{|i| f *= i } << 2..n
return f
}</
Built-in:
<syntaxhighlight lang
=={{header|Simula}}==
<
integer procedure factorial(n);
integer n;
Line 6,371 ⟶ 9,765:
outint(f, 2); outint(factorial(f), 8); outimage
end
end</
{{out}}
<pre>factorials:
Line 6,382 ⟶ 9,776:
=={{header|Sisal}}==
Solution using a fold:
<
function main(x : integer returns integer)
Line 6,391 ⟶ 9,785:
end for
end function</
Simple example using a recursive function:
<
function main(x : integer returns integer)
Line 6,403 ⟶ 9,797:
end if
end function</
=={{header|Slate}}==
This is already implemented in the core language as:
<
"The standard recursive definition."
[
Line 6,414 ⟶ 9,808:
ifTrue: [1]
ifFalse: [n * ((n - 1) factorial)]
].</
Here is another way to implement it:
<
[
n isNegative ifTrue: [error: 'Negative inputs to factorial are invalid.'].
(1 upTo: n by: 1) reduce: [|:a :b| a * b]
].</
{{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
===Iterative with fold===
{{works with|GNU Smalltalk}} {{works with|Smalltalk}}
<
my_factorial [
(self < 2)
Line 6,440 ⟶ 9,858:
7 factorial printNl.
7 my_factorial printNl.</
===Recursive===
<
self < 0 ifTrue: [ self error: '
self isZero ifTrue: [ ^1 ].
^self * ((self - 1)
]
].</
===Recursive (functional)===
Defining a ''local function'' (aka closure) named 'fac':
<syntaxhighlight lang="smalltalk">|fac|
n < 0 ifTrue: [ self error: 'fac is defined for natural numbers' ].
n <= 1
ifTrue: [ 1 ]
ifFalse: [ n * (fac value:(n - 1)) ]
fac value:1000.</syntaxhighlight>
{{works with|Pharo|1.3-13315}}
{{works with|Smalltalk/X}}
<
fac := [ :n | (1 to: n) inject: 1 into: [ :prod :next | prod * next ] ].
fac value: 10.
"3628800"</
{{works with|Smalltalk/X}}
<
fac value:40
-> 815915283247897734345611269596115894272000000000</
Note ¹) 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 6,477 ⟶ 9,899:
Note: Snobol4+ overflows after 7! because of signed short int limitation.
===Recursive===
<
rfact rfact = le(n,0) 1 :s(return)
rfact = n * rfact(n - 1) :(return)
rfact_end</
===Tail-recursive===
<
trfact trfact = le(n,0) f :s(return)
trfact = trfact(n - 1, n * f) :(return)
trfact_end</
===Iterative===
<
ifact ifact = 1
if1 ifact = gt(n,0) n * ifact :f(return)
n = n - 1 :(if1)
ifact_end</
Test and display factorials 0 .. 10
<
output = rfact(i) ' ' trfact(i,1) ' ' ifact(i) :(loop)
end</
{{out}}
<pre>1 1 1
Line 6,509 ⟶ 9,931:
39916800 39916800 39916800</pre>
=={{header|Soda}}==
===Recursive===
<syntaxhighlight lang="soda">
factorial (n : Int) : Int =
if n < 2
then 1
else n * factorial (n - 1)
</syntaxhighlight>
===Tail recursive===
<syntaxhighlight lang="soda">
_tailrec_fact (n : Int) (accum : Int) : Int =
if n < 2
then accum
else _tailrec_fact (n - 1) (n * accum)
factorial (n : Int) : Int =
_tailrec_fact (n) (1)
</syntaxhighlight>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "factorial n" )
@( description, "Write a function to return the factorial of a number." )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure factorial is
fact_pos : constant integer := numerics.value( $1 );
result : natural;
count : natural;
begin
if fact_pos < 0 then
put_line( standard_error, source_info.source_location & ": number must be >= 0" );
command_line.set_exit_status( 192 );
return;
end if;
if fact_pos = 0 then
? 0;
return;
end if;
result := natural( fact_pos );
count := natural( fact_pos - 1 );
for i in reverse 1..count loop
result := @ * i;
end loop;
? result;
end factorial;</syntaxhighlight>
=={{header|Spin}}==
Line 6,515 ⟶ 9,989:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
Line 6,537 ⟶ 10,011:
repeat while n > 0
f *= n
n -= 1</
{{out}}
<pre>1 1 2 6 24 120 720 5040 40320 362880 3628800 </pre>
=={{header|SPL}}==
<
? n!>1, <=1
<= n*fact(n-1)
.</
=={{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!
<
10101000000000010000000000000000 1. Sub. 21
10100000000001100000000000000000 2. c to 5
Line 6,570 ⟶ 10,044:
00000000110101110111100110111111 19. -39916800
00000000001000001100111011000111 20. -479001600
01010000000000000000000000000000 21. 10</
=={{header|Standard ML}}==
===Recursive===
<
if n <= 0 then 1
else n * factorial (n-1)</
The following is tail-recursive, so it is effectively iterative:
<
fun loop (i, accum) =
if i > n then accum
Line 6,584 ⟶ 10,058:
in
loop (1, 1)
end</
=={{header|Stata}}==
Mata has the built-in '''factorial''' function. Here are two implementations.
<
real scalar function fact1(real scalar n) {
if (n<2) return(1)
Line 6,603 ⟶ 10,077:
printf("%f\n",fact1(8))
printf("%f\n",fact2(8))
printf("%f\n",factorial(8))</
=={{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===
<
return n < 2 ? 1 : (2...n).reduce(1, *)
}</
===Recursive===
<
return n < 2 ? 1 : n * factorial(n - 1)
}</
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
fact
if n < 1
return
endif
* n fn fn
- n
call fact
return
start
if i < 20
1 fn
i n
call fact
fn []
+ i
goif
endif
</syntaxhighlight>
=={{header|Tailspin}}==
===Iterative===
<syntaxhighlight lang="tailspin">
templates factorial
when <0..> do
@: 1;
1..$ -> @: $@ * $;
$@ !
end factorial
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="tailspin">
templates factorial
when <=0> do 1 !
when <0..> $ * ($ - 1 -> factorial) !
end factorial
</syntaxhighlight>
=={{header|Tcl}}==
Line 6,619 ⟶ 10,168:
Use Tcl 8.5 for its built-in arbitrary precision integer support.
===Iterative===
<
for {set i $n; set sum 1} {$i >= 2} {incr i -1} {
set sum [expr {$sum * $i}]
}
return $sum
}</
===Recursive===
<
expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]}
}</
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:
<
===Iterative with caching===
<
global fact_cache
if { ! [info exists fact_cache]} {
Line 6,650 ⟶ 10,199:
}
return $sum
}</
===Performance Analysis===
<
puts [rfact 30]
puts [ifact_caching 30]
Line 6,662 ⟶ 10,211:
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]"</
{{out}}
<pre>265252859812191058636308480000000
Line 6,675 ⟶ 10,224:
Note that this only works correctly for factorials that produce correct representations in double precision floating-point numbers.
{{tcllib|math::special}}
<
proc gfact n {
expr {round([::math::special::Gamma [expr {$n+1}]])}
}</
=={{header|TI-
The program stack has only three levels, which means that the recursive approach can be dispensed with.
{| class="wikitable"
! Machine code
! Comment
|-
|
Lbl 0
C.t
x=t
1
STO 0
Lbl 1
RCL 0
×
Dsz
GTO 1
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 ===
<
{
if(%num < 2)
Line 6,708 ⟶ 10,277:
%num *= %a;
return %num;
}</
=== Recursive ===
<
{
if(%num < 2)
return 1;
return %num * Factorial(%num-1);
}</
=={{header|TransFORTH}}==
<
1 SWAP
1 + 1 DO
I * LOOP ;</
=={{header|TUSCRIPT}}==
<
LOOP num=-1,12
IF (num==0,1) THEN
Line 6,740 ⟶ 10,309:
formatnum=CENTER(num,+2," ")
PRINT "factorial of ",formatnum," = ",f
ENDLOOP</
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 6,765 ⟶ 10,334:
Via nPk function:
<
3628800</
===Functional===
<
3628800</
=={{header|UNIX Shell}}==
=== Iterative ===
{{works with|Bourne Shell}}
<
set -- "$1" 1
until test "$1" -lt 2; do
Line 6,782 ⟶ 10,351:
done
echo "$2"
}</
If <code>expr</code> uses 32-bit signed integers, then this function overflows after <code>factorial 12</code>.
Line 6,790 ⟶ 10,359:
{{works with|ksh93}}
{{works with|zsh}}
<
typeset n=$1 f=1 i
for ((i=2; i < n; i++)); do
Line 6,796 ⟶ 10,365:
done
echo $f
}</
* bash and zsh use 64-bit signed integers, overflows after <code>factorial 20</code>.
Line 6,803 ⟶ 10,372:
These solutions fork many processes, because each level of recursion spawns a subshell to capture the output.
{{works with|Almquist Shell}}
<
{
if [ $1 -eq 0 ]
Line 6,809 ⟶ 10,378:
else echo $(($1 * $(factorial $(($1-1)) ) ))
fi
}</
Or in [[Korn Shell|Korn style]]:
Line 6,816 ⟶ 10,385:
{{works with|pdksh}}
{{works with|zsh}}
<
typeset n=$1
(( n < 2 )) && echo 1 && return
echo $(( n * $(factorial $((n-1))) ))
}</
==={{header|C Shell}}===
This is an iterative solution. ''csh'' uses 32-bit signed integers, so this alias overflows after <code>factorial 12</code>.
<
@ factorial_n = $factorial_args[2] \\
@ factorial_i = 1 \\
Line 6,835 ⟶ 10,404:
factorial f 12
echo $f
# => 479001600</
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">Factorial = /×+1⇡</syntaxhighlight>
=={{header|Ursa}}==
{{trans|Python}}
===Iterative===
<
decl int result
set result 1
Line 6,849 ⟶ 10,421:
return result
end
</syntaxhighlight>
===Recursive===
<
decl int z
set z 1
Line 6,858 ⟶ 10,430:
end if
return z
end</
=={{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.
<
good_factorial = ~&?\1! product:-1^lrtPC/~& iota
better_factorial = ~&?\1! ^T(~&lSL,@rS product:-1)+ ~&Z-~^*lrtPC/~& iota</
test program:
<
test = better_factorial* <0,1,2,3,4,5,6,7,8></
{{out}}
<pre><1,1,2,6,24,120,720,5040,40320></pre>
=={{header|
<syntaxhighlight lang="Uxntal">@factorial ( n* -: fact* )
ORAk ?{ POP2 #0001 JMP2r }
DUP2 #0001 SUB2 factorial MUL2
JMP2r</syntaxhighlight>
=={{header|Verbexx}}==
<
// recursive method (requires INTV_T input parm)
// ----------------
Line 6,954 ⟶ 10,528:
iterative 37! = 13763753091226345046315979581580902400000000
recursive 47! = 258623241511168180642964355153611979969197632389120000000000
iterative 47! = 258623241511168180642964355153611979969197632389120000000000</
=={{header|
===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}}==
<
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
Line 7,133 ⟶ 10,630:
Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;
END Behavior ;</
=={{header|
<syntaxhighlight lang="vim">function! Factorial(n)
if a:n < 2
return 1
else
return a:n * Factorial(a:n-1)
endif
endfunction</syntaxhighlight>
=={{header|V (Vlang)}}==
Updated to V (Vlang) version 0.2.2
===Imperative===
<syntaxhighlight lang="go">const max_size = 10
fn factorial_i() {
mut facs := [0].repeat(max_size + 1)
facs[0] = 1
println('The 0-th Factorial number is: 1')
for i := 1; i <= max_size; i++ {
facs[i] = i * facs[i - 1]
num := facs[i]
println('The $i-th Factorial number is: $num')
}
}
fn main() {
factorial_i()
}</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="go">const max_size = 10
fn factorial_r(n int) int {
if n == 0 {
return 1
}
return n * factorial_r(n - 1)
}
fn main() {
for i := 0; i <= max_size; i++ {
println('factorial($i) is: ${factorial_r(i)}')
}
}</syntaxhighlight>
===Tail Recursive===
<syntaxhighlight lang="go">const max_size = 10
fn factorial_tail(n int) int {
sum := 1
return factorial_r(n, sum)
}
fn factorial_r(n int, sum int) int {
if n == 0 {
return sum
}
return factorial_r(n - 1, n * sum )
}
fn main() {
for i := 0; i <= max_size; i++ {
println('factorial($i) is: ${factorial_tail(i)}')
}
}</syntaxhighlight>
===Memoized===
<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
The 1-th Factorial is: 1
The 2-th Factorial is: 2
The 3-th Factorial is: 6
The 4-th Factorial is: 24
The 5-th Factorial is: 120
The 6-th Factorial is: 720
The 7-th Factorial is: 5040
The 8-th Factorial is: 40320
The 9-th Factorial is: 362880
The 10-th Factorial is: 3628800</pre>
=={{header|Wart}}==
===Recursive, all at once===
<
if (n = 0)
1
(n * (fact n-1))</
===Recursive, using cases and pattern matching===
<
(n * (fact n-1))
def (fact 0)
1</
===Iterative, with an explicit loop===
<
ret result 1
for i 1 (i <= n) ++i
result <- result*i</
===Iterative, with a pseudo-generator===
<
def (nums n)
collect+for i 1 (i <= n) ++i
Line 7,290 ⟶ 10,764:
def (fact n)
(reduce (*) nums.n 1)</
=={{header|WDTE}}==
===Recursive===
<
let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1;</
===Iterative===
<
let ! n => s.range 1 (+ n 1) -> s.reduce 1 *;</
=={{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
Number expression:
<syntaxhighlight lang
Folding:
<
; or
@prod @to 10</
Iterative:
<
@var r 1
@for x to n
:!*r x
r
]</
Recursive:
<
fac &{fac n}?{
<n 2 n
Line 7,334 ⟶ 10,913:
[[!fac 10 !facM 10]]
}</
=={{header|Wrapl}}==
===Product===
<
===Recursive===
<
===Folding===
<
=={{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===
<
section .text
Line 7,357 ⟶ 10,966:
mul ecx
loop .factor
ret</
===Recursive===
<
section .text
Line 7,378 ⟶ 10,987:
; base case: return 1
mov eax, 1
ret</
===Tail Recursive===
<
section .text
Line 7,396 ⟶ 11,005:
mul ecx ; accumulator *= n
dec ecx ; n -= 1
jmp .base_case ; tail call</
=={{header|XL}}==
<
N! -> N * (N-1)!</
=={{header|XLISP}}==
<
(if (< x 0)
nil
(if (<= x 1)
1
(* x (factorial (- x 1))) ) ) )</
=={{header|XPL0}}==
<
int N; \range: 0..12
int F, I;
Line 7,421 ⟶ 11,030:
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);</
=={{header|
<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}}==
<
fcn factTail(n,N=1) { // tail recursion
if (n == 0) return(N);
return(self.fcn(n-1,n*N));
}</
<
var BN=Import("zklBigNum");
factTail(BN(42)) : "%,d".fmt(_).println(); // built in as BN(42).factorial()</
{{out}}
<pre>
Line 7,459 ⟶ 11,100:
</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.
|