Factorial: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
|||
(104 intermediate revisions by 49 users not shown) | |||
Line 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 111:
LOOP CP I,L if i>l
BH ENDLOOP then goto endloop
ENDLOOP EQU *
LA R1,R return r
Line 362:
endif.
endform.</syntaxhighlight>
=={{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!}}==
Line 542 ⟶ 558:
=={{header|Agda}}==
<syntaxhighlight lang="agda">
open import Data.Nat using (ℕ ; zero ; suc ; _*_)
factorial : (n : ℕ) → ℕ
factorial zero = 1
factorial (suc n) = (suc n) * (factorial n
</syntaxhighlight>
=={{header|Aime}}==
Line 729 ⟶ 750:
<syntaxhighlight lang="apl"> FACTORIAL 6
720</syntaxhighlight>
{{works with|Dyalog APL}}
A recursive definition is also possible:
<syntaxhighlight lang="apl">
fac←{⍵>1 : ⍵×fac ⍵-1 ⋄ 1}
fac 5
120
</syntaxhighlight>
=={{header|AppleScript}}==
Line 833 ⟶ 861:
{{Out}}
<pre>39916800</pre>
=={{header|Arendelle}}==
Line 1,164 ⟶ 1,172:
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}}==
Line 1,300 ⟶ 1,321:
362880
3628800</pre>
=={{header|bash}}==
Line 1,334 ⟶ 1,335:
}
</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}}
Line 1,349 ⟶ 1,367:
===Recursive===
{{works with|FreeBASIC}}
{{works with|QBasic}}
{{works with|RapidQ}}
Line 1,358 ⟶ 1,377:
END IF
END FUNCTION</syntaxhighlight>
==={{header|Applesoft BASIC}}===
====Iterative====
<syntaxhighlight lang="applesoftbasic">100 N = 4 : GOSUB 200"FACTORIAL
110 PRINT N
120 END
200 N = INT(N)
210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I
220 RETURN</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="applesoftbasic"> 10 A = 768:L = 7
20 DATA 165,157,240,3
30 DATA 32,149,217,96
40 FOR I = A TO A + L
50 READ B: POKE I,B: NEXT
60 H = 256: POKE 12,A / H
70 POKE 11,A - PEEK (12) * H
80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1)
90 PRINT FN FA(4)</syntaxhighlight>http://hoop-la.ca/apple2/2013/usr-if-recursive-fn/
==={{header|BaCon}}===
Overflow occurs at 21 or greater. Negative values treated as 0.
<syntaxhighlight lang="freebasic">' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n"</syntaxhighlight>
{{out}}
<pre>prompt$ ./factorial 0
0! = 1
prompt$ ./factorial 20
20! = 2432902008176640000</pre>
==={{header|BASIC256}}===
====Iterative====
<syntaxhighlight lang="vb">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
factorial = 1
if n > 0 then
for p = 1 to n
factorial *= p
next p
end if
end function</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="basic256">print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
if n > 0 then
factorial = n * factorial(n-1)
else
factorial = 1
end if
end function</syntaxhighlight>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
18! is the largest that doesn't overflow.
<syntaxhighlight lang="bbcbasic"> *FLOAT64
@% = &1010
PRINT FNfactorial(18)
END
DEF FNfactorial(n)
IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)</syntaxhighlight>
{{out}}
<pre>6402373705728000</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
====Iterative====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factoriali(i)
140 next i
150 sub factoriali(n) : 'Iterative
160 f = 1
170 if n > 1 then
180 for j = 2 to n
190 f = f*j
200 next j
210 endif
220 factoriali = f
230 end sub</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="qbasic">100 cls
110 limite = 13
120 for i = 0 to limite
130 print right$(str$(i),2);"! = ";tab (6);factorialr(i)
140 next i
150 sub factorialr(n) : 'Recursive
160 if n < 2 then
170 f = 1
180 else
190 f = n*factorialr(n-1)
200 endif
210 factorialr = f
220 end sub</syntaxhighlight>
==={{header|Commodore BASIC}}===
Line 1,376 ⟶ 1,510:
====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
Line 1,410 ⟶ 1,542:
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>
Line 1,429 ⟶ 1,696:
150 LET FACT=F
160 END DEF</syntaxhighlight>
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb"> for i =0 to 40
print " FactorialI( "; using( "####", i); ") = "; factorialI( i)
print " FactorialR( "; using( "####", i); ") = "; factorialR( i)
next i
wait
function factorialI( n)
if n >1 then
f =1
For i = 2 To n
f = f * i
Next i
else
f =1
end if
factorialI =f
end function
function factorialR( n)
if n <2 then
f =1
else
f =n *factorialR( n -1)
end if
factorialR =f
end function
end</syntaxhighlight>
==={{header|Microsoft Small Basic}}===
<syntaxhighlight lang="smallbasic">'Factorial - smallbasic - 05/01/2019
For n = 1 To 25
f = 1
For i = 1 To n
f = f * i
EndFor
TextWindow.WriteLine("Factorial(" + n + ")=" + f)
EndFor</syntaxhighlight>
{{out}}
<pre>
Factorial(25)=15511210043330985984000000
</pre>
==={{header|Minimal BASIC}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX_Basic}}
<syntaxhighlight lang="qbasic">10 PRINT "ENTER AN INTEGER:";
20 INPUT N
30 LET F = 1
40 FOR K = 1 TO N
50 LET F = F * K
60 NEXT K
70 PRINT F
80 END</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|PC-BASIC|any}}
<syntaxhighlight lang="qbasic">100 CLS
110 LIMITE = 13
120 FOR N = 0 TO LIMITE
130 PRINT RIGHT$(STR$(N),2);"! = ";
135 GOSUB 150
137 PRINT I
140 NEXT N
145 END
150 'factorial iterative
160 I = 1
170 IF N > 1 THEN FOR J = 2 TO N : I = I*J : NEXT J
230 RETURN</syntaxhighlight>
==={{header|Palo Alto Tiny BASIC}}===
<syntaxhighlight lang="basic">
10 REM FACTORIAL
20 INPUT "ENTER AN INTEGER"N
30 LET F=1
40 FOR K=1 TO N
50 LET F=F*K
60 NEXT K
70 PRINT F
80 STOP
</syntaxhighlight>
{{out}}
<pre>
ENTER AN INTEGER:7
5040
</pre>
==={{header|PowerBASIC}}===
<syntaxhighlight lang="powerbasic">function fact1#(n%)
local i%,r#
r#=1
for i%=1 to n%
r#=r#*i%
next
fact1#=r#
end function
function fact2#(n%)
if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n%
end function
for i%=1 to 20
print i%,fact1#(i%),fact2#(i%)
next</syntaxhighlight>
==={{header|PureBasic}}===
====Iterative====
<syntaxhighlight lang="purebasic">Procedure factorial(n)
Protected i, f = 1
For i = 2 To n
f = f * i
Next
ProcedureReturn f
EndProcedure</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="purebasic">Procedure Factorial(n)
If n < 2
ProcedureReturn 1
Else
ProcedureReturn n * Factorial(n - 1)
EndIf
EndProcedure</syntaxhighlight>
==={{header|QB64}}===
<syntaxhighlight lang="qbasic">
REDIM fac#(0)
Factorial fac#(), 655, 10, power#
PRINT power#
SUB Factorial (fac#(), n&, numdigits%, power#)
power# = 0
fac#(0) = 1
remain# = 0
stx& = 0
slog# = 0
NumDiv# = 10 ^ numdigits%
FOR fac# = 1 TO n&
slog# = slog# + LOG(fac#) / LOG(10)
FOR x& = 0 TO stx&
fac#(x&) = fac#(x&) * fac# + remain#
tx# = fac#(x&) MOD NumDiv#
remain# = (fac#(x&) - tx#) / NumDiv#
fac#(x&) = tx#
NEXT
IF remain# > 0 THEN
stx& = UBOUND(fac#) + 1
REDIM _PRESERVE fac#(stx&)
fac#(stx&) = remain#
remain# = 0
END IF
NEXT
scanz& = LBOUND(fac#)
DO
IF scanz& < UBOUND(fac#) THEN
IF fac#(scanz&) THEN
EXIT DO
ELSE
scanz& = scanz& + 1
END IF
ELSE
EXIT DO
END IF
LOOP
FOR x& = UBOUND(fac#) TO scanz& STEP -1
m$ = LTRIM$(RTRIM$(STR$(fac#(x&))))
IF x& < UBOUND(fac#) THEN
WHILE LEN(m$) < numdigits%
m$ = "0" + m$
WEND
END IF
PRINT m$; " ";
power# = power# + LEN(m$)
NEXT
power# = power# + (scanz& * numdigits%) - 1
PRINT slog#
END SUB
</syntaxhighlight>
====QB64_2022====
<syntaxhighlight lang="qbasic">
N = 18: DIM F AS DOUBLE ' Factorial.bas from Russia
F = 1: FOR I = 1 TO N: F = F * I: NEXT: PRINT F
'N = 5 F = 120
'N = 18 F = 6402373705728000
</syntaxhighlight>
==={{header|Quite BASIC}}===
{{works with|QBasic|1.1}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX_Basic}}
<syntaxhighlight lang="qbasic">10 CLS
20 INPUT "Enter an integer:"; N
30 LET F = 1
40 FOR K = 1 TO N
50 LET F = F * K
60 NEXT K
70 PRINT F
80 END</syntaxhighlight>
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 0 to 100
print " fctrI(";right$("00";str$(i),2); ") = "; fctrI(i)
print " fctrR(";right$("00";str$(i),2); ") = "; fctrR(i)
next i
end
function fctrI(n)
fctrI = 1
if n >1 then
for i = 2 To n
fctrI = fctrI * i
next i
end if
end function
function fctrR(n)
fctrR = 1
if n > 1 then fctrR = n * fctrR(n -1)
end function</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
Line 1,458 ⟶ 1,955:
{{out}}
<pre>6227020800</pre>
==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
n = 10
factorial = 1
for ii = 2 to n
factorial = factorial * ii
next
print factorial
</syntaxhighlight>
==={{header|TI-83 BASIC}}===
TI-83 BASIC has a built-in factorial operator: x! is the factorial of x.
An other way is to use a combination of prod() and seq() functions:
<syntaxhighlight lang="ti89b">10→N
N! ---> 362880
prod(seq(I,I,1,N)) ---> 362880</syntaxhighlight>
Note: maximum integer value is:
13! ---> 6227020800
==={{header|TI-89 BASIC}}===
TI-89 BASIC also has the factorial function built in: x! is the factorial of x.
<syntaxhighlight lang="ti89b">factorial(x)
Func
Return Π(y,y,1,x)
EndFunc</syntaxhighlight>
Π is the standard product operator: <math>\overbrace{\Pi(\mathrm{expr},i,a,b)}^{\mathrm{TI-89}} = \overbrace{\prod_{i=a}^b \mathrm{expr}}^{\text{Math notation}}</math>
==={{Header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 LET F = 1
20 PRINT "Enter an integer."
30 INPUT N
Line 1,467 ⟶ 1,994:
60 LET N = N - 1
70 GOTO 40
80 PRINT F
90 END</syntaxhighlight>
==={{header|
====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
LET FNfactorial = n * FNfactorial(n-1)
END IF
END DEF
END</syntaxhighlight>
===
<syntaxhighlight lang="
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}}==
Line 1,507 ⟶ 2,302:
pause
exit</syntaxhighlight>
=={{header|bc}}==
Line 1,595 ⟶ 2,376:
^-1:_$>\:|
@.$<</syntaxhighlight>
=={{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}}==
Line 1,676 ⟶ 2,461:
true? x == 0 1 { x * factorial(x - 1)}
}</syntaxhighlight>
=={{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,888 ⟶ 2,685:
===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;
Line 1,902 ⟶ 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 2,270 ⟶ 3,091:
=== Folding ===
<syntaxhighlight lang="lisp">(defn factorial [x]
(apply *' (range 2 (inc x))))</syntaxhighlight>
=== Recursive ===
Line 2,276 ⟶ 3,097:
(if (< x 2)
1
(*' x (factorial (dec x)))))</syntaxhighlight>
=== Tail recursive ===
Line 2,284 ⟶ 3,105:
(if (< x 2)
acc
(recur (dec x) (*' acc x)))))</syntaxhighlight>
=== 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}}==
Line 2,579 ⟶ 3,408:
x: 5</syntaxhighlight>
=={{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}}==
Line 2,970 ⟶ 3,808:
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
func factorial n .
return r
.
=={{header|EchoLisp}}==
Line 3,018 ⟶ 3,856:
→ 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}}==
Line 3,139 ⟶ 4,100:
=={{header|Elm}}==
===
<syntaxhighlight lang="elm">
Line 3,147 ⟶ 4,108:
</syntaxhighlight>
===
<syntaxhighlight lang="elm">
Line 3,159 ⟶ 4,120:
</syntaxhighlight>
===
<syntaxhighlight lang="elm">
Line 3,202 ⟶ 4,163:
=>
"265252859812191058636308480000000"</syntaxhighlight>
=={{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}}==
Line 3,611 ⟶ 4,614:
RETURN
END</syntaxhighlight>
=={{header|friendly interactive shell}}==
Line 3,771 ⟶ 4,734:
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"Factorial", ( 0, 0, 300, 550 )
local fn factorialIterative( n as long ) as double
Line 3,805 ⟶ 4,769:
next
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Iterative: 0 = 1
Line 3,849 ⟶ 4,813:
</pre>
=={{header|GAP}}==
Line 4,120 ⟶ 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}}==
Line 4,369 ⟶ 5,309:
=={{header|Inform 6}}==
<syntaxhighlight lang="inform6">[ factorial n;
if (n == 0)
return 1;
else
return n * factorial(n - 1);
];</syntaxhighlight>
=={{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}}==
Line 4,398 ⟶ 5,358:
7710530113353860041446393977750283605955564018160102391634109940339708518270930693670907697955390330926478612242306774446597851526397454014801846531749097625044706382742591201733097017026108750929188168469858421505936237186038616420630788341172340985137252...</syntaxhighlight>
</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}}==
Line 5,009 ⟶ 5,989:
-> 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>
Line 5,027 ⟶ 6,052:
=={{header|langur}}==
=== Folding ===
<syntaxhighlight lang="langur">
val factorial = fn n: fold(fn{*}, 2 .. n)
writeln factorial(7)
</syntaxhighlight>
=== Recursive ===
<syntaxhighlight lang="langur">
writeln factorial(7)
</syntaxhighlight>
=== Iterative ===
<syntaxhighlight lang="langur">
val factorial = fn(i) {
for x in 2 .
answer *= x
}
}
writeln factorial(7)
</syntaxhighlight>
=== Iterative Folding ===
<syntaxhighlight lang="langur">
writeln
</syntaxhighlight>
{{out}}
Line 5,095 ⟶ 6,124:
acc.
}.</syntaxhighlight>
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
n is number
procedure:
sub factorial
parameters:
n is number
result is number
local data:
i is number
m is number
procedure:
store 1 in result
in m solve n + 1
for i from 1 to m step 1 do
multiply result by i in result
repeat
end sub
create statement "get factorial of $ in $" executing factorial
get factorial of 5 in n
display n lf
</syntaxhighlight>
{{out}}
<pre>
120
</pre>
=={{header|Lean}}==
<syntaxhighlight lang="lean">
def factorial (n : Nat) : Nat :=
match n with
| 0 => 1
| (k + 1) => (k + 1) * factorial (k)
</syntaxhighlight>
=={{header|LFE}}==
Line 5,175 ⟶ 6,242:
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}}==
Line 5,302 ⟶ 6,338:
// iterative
function factorialit n
if n > 1 then
repeat with i = 1 to n
Line 5,787 ⟶ 6,823:
Example output:
<syntaxhighlight lang="bash">factorial(100) = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</syntaxhighlight>
=={{header|min}}==
Line 6,039 ⟶ 7,061:
RETURN result;
END FactRec;</syntaxhighlight>
=={{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}}==
Line 6,262 ⟶ 7,296:
4 factorial . ( => 24 )
10 factorial . ( => 3628800 )</syntaxhighlight>
=={{header|Nu}}==
<syntaxhighlight lang="nu">
def 'math factorial' [] {[$in 1] | math max | 1..$in | math product}
..10 | each {math factorial}
</syntaxhighlight>
{{out}}
<pre>
╭────┬─────────╮
│ 0 │ 1 │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 6 │
│ 4 │ 24 │
│ 5 │ 120 │
│ 6 │ 720 │
│ 7 │ 5040 │
│ 8 │ 40320 │
│ 9 │ 362880 │
│ 10 │ 3628800 │
╰────┴─────────╯
</pre>
=={{header|Nyquist}}==
Line 6,277 ⟶ 7,334:
(* n (factorial (1- n)))))</syntaxhighlight>
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="
MODULE Factorial;
IMPORT
Line 6,344 ⟶ 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>
Line 6,435 ⟶ 7,562:
<pre>30414093201713378043612608166064768844377641568960512000000000000 </pre>
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}}==
Line 6,711 ⟶ 7,856:
factorial := n*factorial(n-1)
end;</syntaxhighlight>
=={{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}}==
Line 7,010 ⟶ 8,226:
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}}==
Line 7,024 ⟶ 8,265:
return (F);
end factorial;</syntaxhighlight>
=={{header|PL/SQL}}==
Line 7,197 ⟶ 8,437:
{{libheader|initlib}}
<syntaxhighlight lang="postscript">/myfact {{dup 0 eq} {pop 1} {dup pred} {mul} linrec}.</syntaxhighlight>
=={{header|PowerShell}}==
Line 7,356 ⟶ 8,577:
loop p n = if n>0 then loop (p*n) (n-1) else p;
end;</syntaxhighlight>
=={{header|Python}}==
Line 7,505 ⟶ 8,708:
===Recursive===
<syntaxhighlight lang="q">f:{$[x=1;1;x*.z.s x-1]}</syntaxhighlight>
=={{header|Quackery}}==
Line 7,834 ⟶ 8,973:
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}}==
Line 8,056 ⟶ 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}}==
Line 8,110 ⟶ 9,311:
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 8,166 ⟶ 9,390:
inject: 2.500000 0.130000 2.630000 ( 2.641898)
reduce: 2.110000 0.230000 2.340000 ( 2.338166)</pre>
=={{header|Rust}}==
Line 8,240 ⟶ 9,443:
end;
end;</syntaxhighlight>
=={{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 8,245 ⟶ 9,500:
===Imperative===
An imperative style using a mutable variable:
<syntaxhighlight lang="scala">
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===
Line 8,274 ⟶ 9,535:
===Folding===
Using folding:
<syntaxhighlight lang="scala">
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 8,294 ⟶ 9,559:
=={{header|Scheme}}==
===Recursive===
<syntaxhighlight lang="scheme">
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))
</syntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<syntaxhighlight lang="scheme">
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))
</syntaxhighlight>
===Iterative===
<syntaxhighlight lang="scheme">
(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 8,333 ⟶ 9,607:
(factorial 8)
;40320
</syntaxhighlight>
===Pragmatic===
<syntaxhighlight lang="scheme">
(define (range n)
(let ((lst '()))
(do ((i 1 (+ i 1)))
((= i (+ n 1)))
(set! lst (cons i lst)))
(reverse lst)))
(define (fact n)
(apply * (range n)))
</syntaxhighlight>
=={{header|Scilab}}==
Line 8,543 ⟶ 9,832:
<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}}==
Line 8,631 ⟶ 9,944:
3628800 3628800 3628800
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 8,726 ⟶ 10,092:
printf("%f\n",fact2(8))
printf("%f\n",factorial(8))</syntaxhighlight>
=={{header|SuperCollider}}==
===Iterative===
<syntaxhighlight lang="SuperCollider">
f = { |n| (1..n).product };
f.(10);
// for numbers larger than 12, use 64 bit float
// instead of 32 bit integers, because the integer range is exceeded
// (1..n) returns an array of floats when n is a float
f.(20.0);
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="SuperCollider">
f = { |n| if(n < 2) { 1 } { n * f.(n - 1) } };
f.(10);
</syntaxhighlight>
=={{header|Swift}}==
Line 8,845 ⟶ 10,244:
}</syntaxhighlight>
=={{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}}==
Line 8,887 ⟶ 10,306:
1 + 1 DO
I * LOOP ;</syntaxhighlight>
=={{header|TUSCRIPT}}==
Line 9,023 ⟶ 10,419:
echo $f
# => 479001600</syntaxhighlight>
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">Factorial = /×+1⇡</syntaxhighlight>
=={{header|Ursa}}==
Line 9,060 ⟶ 10,459:
<pre><1,1,2,6,24,120,720,5040,40320></pre>
=={{header|
<syntaxhighlight lang="
ORAk ?{ POP2 #0001 JMP2r }
DUP2 #0001 SUB2 factorial MUL2
JMP2r</syntaxhighlight>
=={{header|Verbexx}}==
Line 9,347 ⟶ 10,655:
endfunction</syntaxhighlight>
=={{header|
Updated to V (Vlang) version 0.2.2
===Imperative===
<syntaxhighlight lang="go">const max_size = 10
Line 9,759 ⟶ 10,940:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<syntaxhighlight lang="
import "./big" for BigInt
class Factorial {
Line 9,865 ⟶ 11,046:
return if N<2 then 1 else N*FactRecur(N-1);</syntaxhighlight>
=={{header|
<syntaxhighlight lang="
#!/usr/bin/env ys-0
defn main(n):
say: "$n! = $factorial(n)"
defn factorial(x):
apply *: 2 .. x
=={{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
else if (n < 0)
null
Line 9,900 ⟶ 11,070:
var fac: Num = 1;
while (i <= n) : (i += 1) {
if (tmp[1] !=
break :calc null; // overflow
fac = tmp[0];
} else break :calc fac;
};
Line 9,907 ⟶ 11,079:
pub fn main() !void {
try stdout.print("
try stdout.print("
try stdout.print("
try stdout.print("
try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible
try stdout.print("34! = {?}\n", .{factorial(i128, 34)}); // will overflow
}
</syntaxhighlight>
Line 9,940 ⟶ 11,114:
</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.
|