Factorial: Difference between revisions

22,563 bytes added ,  13 days ago
m
fixed incorrect placement
No edit summary
m (fixed incorrect placement)
 
(87 intermediate revisions by 41 users not shown)
Line 86:
L R15,=A(FACT)
BALR R14,R15 call fact(n)
ZAP F,0(L'R,R1) f=fact(n)
DUMP EQU *
MVC S,MASK
ED S,N
MVC WTOBUF+5(2),S+30
MVC S,MASK
ED S,F
MVC WTOBUF+9(32),S
WTO MF=(E,WTOMSG)
AP N,=P'1' n=n+1
B LOOPN
ENDLOOPN EQU *
RETURN EQU *
Line 111:
LOOP CP I,L if i>l
BH ENDLOOP then goto endloop
MP R,I r=r*i
AP I,=P'1' i=i+1
B LOOP
ENDLOOP EQU *
LA R1,R return r
Line 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">factorialmodule :Factorial ℕ → ℕwhere
 
open import Data.Nat using (ℕ ; zero ; suc ; _*_)
 
factorial : (n : ℕ) → ℕ
factorial zero = 1
factorial (suc n) = (suc n) * (factorial n</syntaxhighlight>)
</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 1,144 ⟶ 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,294 ⟶ 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,309 ⟶ 1,367:
 
===Recursive===
{{works with|FreeBASIC}}
{{works with|QBasic}}
{{works with|RapidQ}}
Line 1,400 ⟶ 1,459:
{{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,451 ⟶ 1,543:
13 ! = 6.2270208E+09
</pre>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">'accurate between 1-12
 
print "version 1 without function"
 
for i = 1 to 12
 
let n = i
let f = 1
 
do
 
let f = f * n
let n = n - 1
 
loop n > 0
 
print f, " ",
wait
 
next i
 
print newline, newline, "version 2 with function"
 
for i = 1 to 12
 
print factorial(i), " ",
 
next i</syntaxhighlight>
{{out| Output}}<pre>version 1 without function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600
 
version 2 with function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 </pre>
 
==={{header|FreeBASIC}}===
Line 1,493 ⟶ 1,620:
10 => 3628800</pre>
 
==={{header|FutureBasicFTCBASIC}}===
<syntaxhighlight lang="futurebasicbasic">windowdefine f = 1, @"Factorial",n (= 0, 0, 300, 550 )
 
print "Factorial"
local fn factorialIterative( n as long ) as double
print "Enter an integer: " \
double f
long i
 
input n
if ( n > 1 )
f = 1
for i = 2 to n
f = f * i
next
else
f = 1
end if
end fn = f
 
do
local fn factorialRecursive( n as long ) as double
double f
 
let f if= (f * n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
 
-1 n
long i
 
forloop in => 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next
 
print f
HandleEvents</syntaxhighlight>
pause
end</syntaxhighlight>
 
Output:
<pre>
Iterative: 0 = 1
Recursive: 0 = 1
 
Iterative: 1 = 1
Recursive: 1 = 1
 
Iterative: 2 = 2
Recursive: 2 = 2
 
Iterative: 3 = 6
Recursive: 3 = 6
 
Iterative: 4 = 24
Recursive: 4 = 24
 
Iterative: 5 = 120
Recursive: 5 = 120
 
Iterative: 6 = 720
Recursive: 6 = 720
 
Iterative: 7 = 5040
Recursive: 7 = 5040
 
Iterative: 8 = 40320
Recursive: 8 = 40320
 
Iterative: 9 = 362880
Recursive: 9 = 362880
 
Iterative: 10 = 3628800
Recursive: 10 = 3628800
 
Iterative: 11 = 39916800
Recursive: 11 = 39916800
 
Iterative: 12 = 479001600
Recursive: 12 = 479001600
</pre>
 
==={{header|Gambas}}===
Line 1,672 ⟶ 1,741:
<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>
 
Line 1,773 ⟶ 1,891:
'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}}===
Line 2,233 ⟶ 2,365:
^-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 2,314 ⟶ 2,450:
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 2,932 ⟶ 3,080:
=== Folding ===
<syntaxhighlight lang="lisp">(defn factorial [x]
(apply *' (range 2 (inc x))))</syntaxhighlight>
 
=== Recursive ===
Line 2,938 ⟶ 3,086:
(if (< x 2)
1
(*' x (factorial (dec x)))))</syntaxhighlight>
 
=== Tail recursive ===
Line 2,946 ⟶ 3,094:
(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 3,241 ⟶ 3,397:
 
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 3,633 ⟶ 3,798:
 
<syntaxhighlight lang="text">
func factorial n . r .
r = 1
for i = 2 to n
r *= i
.
return r
.
callprint factorial 7 r
print r
</syntaxhighlight>
 
Line 3,680 ⟶ 3,845:
→ 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,801 ⟶ 4,089:
=={{header|Elm}}==
 
==={{header|Recursive}}===
 
<syntaxhighlight lang="elm">
Line 3,809 ⟶ 4,097:
</syntaxhighlight>
 
==={{header|Tail Recursive}}===
 
<syntaxhighlight lang="elm">
Line 3,821 ⟶ 4,109:
</syntaxhighlight>
 
==={{header|Functional}}===
 
<syntaxhighlight lang="elm">
Line 3,864 ⟶ 4,152:
=>
"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 4,391 ⟶ 4,721:
in out
</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"Factorial", ( 0, 0, 300, 550 )
 
local fn factorialIterative( n as long ) as double
double f
long i
 
if ( n > 1 )
f = 1
for i = 2 to n
f = f * i
next
else
f = 1
end if
end fn = f
 
local fn factorialRecursive( n as long ) as double
double f
 
if ( n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
 
long i
 
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
Recursive: 0 = 1
 
Iterative: 1 = 1
Recursive: 1 = 1
 
Iterative: 2 = 2
Recursive: 2 = 2
 
Iterative: 3 = 6
Recursive: 3 = 6
 
Iterative: 4 = 24
Recursive: 4 = 24
 
Iterative: 5 = 120
Recursive: 5 = 120
 
Iterative: 6 = 720
Recursive: 6 = 720
 
Iterative: 7 = 5040
Recursive: 7 = 5040
 
Iterative: 8 = 40320
Recursive: 8 = 40320
 
Iterative: 9 = 362880
Recursive: 9 = 362880
 
Iterative: 10 = 3628800
Recursive: 10 = 3628800
 
Iterative: 11 = 39916800
Recursive: 11 = 39916800
 
Iterative: 12 = 479001600
Recursive: 12 = 479001600
</pre>
 
 
=={{header|GAP}}==
Line 4,626 ⟶ 5,037:
}
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>
 
Line 4,876 ⟶ 5,298:
=={{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,905 ⟶ 5,347:
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,516 ⟶ 5,978:
-> 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,534 ⟶ 6,041:
=={{header|langur}}==
=== Folding ===
<syntaxhighlight lang="langur">val .factorial = ffn(.n) fold(ffn{*}, .x x2 .y, pseries. .n)
writeln .factorial(7)</syntaxhighlight>
 
{{works with|langur|0.6.13}}
<syntaxhighlight lang="langur">val .factorial = f fold(f{x}, 2 to .n)
writeln .factorial(7)</syntaxhighlight>
 
=== Recursive ===
<syntaxhighlight lang="langur">val .factorial = ffn(.x) { if(.x < 2: 1; .x x* self(.x - 1)) }
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative ===
<syntaxhighlight lang="langur">val .factorial = ffn(.i) {
var .answer = 1
for .x in 2 to.. .i {
.answer x*= .x
}
.answer
}
 
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative Folding ===
<syntaxhighlight lang="langur">val .factorial = fn(.n) { for[=1] .x in .n { _for *= .x } }
{{works with|langur|0.7.0}}
<syntaxhighlight lang="langur">val .factorial = f(.n) for[=1] .x in .n { _for x= .x }
writeln .factorial(7)</syntaxhighlight>
 
Line 5,602 ⟶ 6,105:
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,778 ⟶ 6,319:
// iterative
function factorialit n
put 1 into f
if n > 1 then
repeat with i = 1 to n
Line 6,736 ⟶ 7,277:
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,751 ⟶ 7,315:
(* n (factorial (1- n)))))</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="oberon2modula2">
MODULE Factorial;
IMPORT
Line 6,818 ⟶ 7,382:
Recursive 8! =40320
Recursive 9! =362880
</pre>
 
=={{header|Oberon-07}}==
Almost identical to the Oberon-2 sample, with minor output formatting differences.<br/>
Oberon-2 allows single or double quotes to delimit strings whereas Oberon-07 only allows double quotes. Also, the LONGINT type does not exist in Oberon-07 (though some compilers may accept is as a synonym for INTEGER).
<syntaxhighlight lang="modula2">
MODULE Factorial;
IMPORT
Out;
 
VAR
i: INTEGER;
 
PROCEDURE Iterative(n: INTEGER): INTEGER;
VAR
i, r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
FOR i := n TO 2 BY -1 DO
r := r * i
END;
RETURN r
END Iterative;
 
PROCEDURE Recursive(n: INTEGER): INTEGER;
VAR
r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
IF n > 1 THEN
r := n * Recursive(n - 1)
END;
RETURN r
END Recursive;
 
BEGIN
FOR i := 0 TO 9 DO
Out.String("Iterative ");Out.Int(i,0);Out.String("! =");Out.Int(Iterative(i),8);Out.Ln;
END;
Out.Ln;
FOR i := 0 TO 9 DO
Out.String("Recursive ");Out.Int(i,0);Out.String("! =");Out.Int(Recursive(i),8);Out.Ln;
END
END Factorial.
</syntaxhighlight>
{{out}}
<pre>
Iterative 0! = 1
Iterative 1! = 1
Iterative 2! = 2
Iterative 3! = 6
Iterative 4! = 24
Iterative 5! = 120
Iterative 6! = 720
Iterative 7! = 5040
Iterative 8! = 40320
Iterative 9! = 362880
 
Recursive 0! = 1
Recursive 1! = 1
Recursive 2! = 2
Recursive 3! = 6
Recursive 4! = 24
Recursive 5! = 120
Recursive 6! = 720
Recursive 7! = 5040
Recursive 8! = 40320
Recursive 9! = 362880
</pre>
 
Line 7,203 ⟶ 7,837:
factorial := n*factorial(n-1)
end;</syntaxhighlight>
 
=={{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,502 ⟶ 8,168:
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,516 ⟶ 8,207:
return (F);
end factorial;</syntaxhighlight>
 
 
=={{header|PL/SQL}}==
Line 8,225 ⟶ 8,915:
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,447 ⟶ 9,165:
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
</pre>
 
=={{header|Rhovas}}==
Solutions support arbitrarily large numbers as Rhovas's <code>Integer</code> type is arbitrary-precision (Java <code>BigInteger</code>). Additional notes:
* <code>require num >= 0;</code> asserts input range preconditions, throwing on negative numbers
 
===Iterative===
Standard iterative solution using a <code>for</code> loop:
* <code>range(2, num, :incl)</code> creates an inclusive range (<code>2 <= i <= num</code>) for iteration
 
<syntaxhighlight lang="scala">
func factorial(num: Integer): Integer {
require num >= 0;
var result = 1;
for (val i in range(2, num, :incl)) {
result = result * i;
}
return result;
}
</syntaxhighlight>
 
===Recursive===
Standard recursive solution using a pattern matching approach:
* <code>match</code> without arguments is a ''conditional match'', which works like <code>if/else</code> chains.
* Rhovas doesn't perform tail-call optimization yet, hence why this solution isn't tail recursive.
 
<syntaxhighlight lang="scala">
func factorial(num: Integer): Integer {
require num >= 0;
match {
num == 0: return 1;
else: return num * factorial(num - 1);
}
}
</syntaxhighlight>
 
=={{header|Ring}}==
Line 8,501 ⟶ 9,253:
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,610 ⟶ 9,385:
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,615 ⟶ 9,442:
===Imperative===
An imperative style using a mutable variable:
<syntaxhighlight lang="scala">def factorial(n: Int)={
def factorial(n: Int) = {
var res = 1
for (i <- 1 to n)
res *= i
res
}
}</syntaxhighlight>
</syntaxhighlight>
 
===Recursive===
Using naive recursion:
<syntaxhighlight lang="scala">def factorial(n: Int): Int =
def if factorial(n: == 0Int): 1Int =
if (n < 1) 1
else n * factorial(n-1)</syntaxhighlight>
else n * factorial(n - 1)
</syntaxhighlight>
 
Using tail recursion with a helper function:
<syntaxhighlight lang="scala">def factorial(n: Int) = {
def factorial(n: Int) = {
@tailrec def fact(x: Int, acc: Int): Int = {
if (x < 2) acc else fact(x - 1, acc * x)
}
fact(n, 1)
}
}</syntaxhighlight>
</syntaxhighlight>
 
===Stdlib .product===
Line 8,644 ⟶ 9,477:
===Folding===
Using folding:
<syntaxhighlight lang="scala">def factorial(n: Int) =
def factorial(n: Int) =
(2 to n).foldLeft(1)(_ * _)</syntaxhighlight>
(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 {
implicit def IntToFac(i : Int) = new {
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}
}</syntaxhighlight>
</syntaxhighlight>
 
{{out | Example used in the REPL}}
Line 8,664 ⟶ 9,501:
=={{header|Scheme}}==
===Recursive===
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))</syntaxhighlight>
</syntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))</syntaxhighlight>
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(do ((i 1 (+ i 1))
(accum 1 (* accum i)))
((> i n) accum)))</syntaxhighlight>
</syntaxhighlight>
 
===Folding===
<syntaxhighlight lang="scheme">;Using a generator and a function that apply generated values to a function taking two arguments
;Using a generator and a function that apply generated values to a function taking two arguments
 
;A generator knows commands 'next? and 'next
Line 8,703 ⟶ 9,549:
 
(factorial 8)
;40320</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Scilab}}==
Line 9,025 ⟶ 9,872:
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 9,120 ⟶ 10,020:
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 9,238 ⟶ 10,171:
expr {round([::math::special::Gamma [expr {$n+1}]])}
}</syntaxhighlight>
 
=={{header|TI-57}}==
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 9,376 ⟶ 10,347:
echo $f
# => 479001600</syntaxhighlight>
 
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">Factorial = /×+1⇡</syntaxhighlight>
 
=={{header|Ursa}}==
Line 9,412 ⟶ 10,386:
{{out}}
<pre><1,1,2,6,24,120,720,5040,40320></pre>
 
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">@factorial ( n* -: fact* )
ORAk ?{ POP2 #0001 JMP2r }
DUP2 #0001 SUB2 factorial MUL2
JMP2r</syntaxhighlight>
 
=={{header|Verbexx}}==
Line 9,888 ⟶ 10,868:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
import "./big" for BigInt
 
class Factorial {
Line 9,993 ⟶ 10,973:
int N; \range: 0..12
return if N<2 then 1 else N*FactRecur(N-1);</syntaxhighlight>
 
=={{header|YAMLScript}}==
<syntaxhighlight lang="yaml">
#!/usr/bin/env ys-0
 
defn main(n):
say: "$n! = $factorial(n)"
 
defn factorial(x):
apply *: 2 .. x
</syntaxhighlight>
 
=={{header|Zig}}==
{{Works with|Zig|0.11.0}}
Supports all integer data types, and checks for both overflow and negative numbers; returns null when there is a domain error.
<syntaxhighlight lang="zig">
const stdout = @import("std").io.getStdOut().outStream();
 
pub fn factorial(comptime Num: type, n: i8) ?Num {
return if (@typeInfo(Num) != .Int)
@compileError("factorial called with numnon-integral type: " ++ @typeName(Num))
else if (n < 0)
null
Line 10,008 ⟶ 10,998:
var fac: Num = 1;
while (i <= n) : (i += 1) {
ifconst tmp = (@mulWithOverflow(Num, fac, i, &fac));
if (tmp[1] != break :calc null;0)
break :calc null; // overflow
fac = tmp[0];
} else break :calc fac;
};
Line 10,015 ⟶ 11,007:
 
pub fn main() !void {
tryconst stdout.print("-1! = {}\n@import(", std").{factorialio.getStdOut(i32, -1)}.writer();
 
try stdout.print("0! = {}\n", .{factorial(i32, 0)});
try stdout.print("5-1! = {?}\n", .{factorial(i32, 5-1)});
try stdout.print("330!(64 bit) = {?}\n", .{factorial(i64i32, 330)}); // not vailid i64 factorial
try stdout.print("335! = {?}\n", .{factorial(i128i32, 335)}); // biggest facorial possible
try stdout.print("3433!(64 bit) = {?}\n", .{factorial(i128i64, 3433)}); // willnot overflowvalid 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>
18

edits