Factorial: Difference between revisions
Content deleted Content added
(108 intermediate revisions by 52 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 50:
=={{header|11l}}==
<
V result = 1
L(i) 2..n
Line 57:
L(n) 0..5
print(n‘ ’factorial(n))</
{{out}}
Line 71:
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<
USING FACTO,R13
SAVEAREA B STM-SAVEAREA(R15)
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 134:
LTORG
YREGS
END FACTO</
{{out}}
<pre>FACT(29)= 8841761993739701954543616000000 </pre>
Line 141:
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.
<
;input: D0.W: number you wish to get the factorial of.
;output: D0.L
Line 212:
MOVEM.L (SP)+,D2-D7
RTS
</syntaxhighlight>
{{out}}
Line 219:
=={{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 */
Line 331:
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 342:
=={{header|ABAP}}==
===Iterative===
<
data: lv_res type i value 1.
do iv_val times.
Line 349:
iv_val = lv_res.
endform.</
===Recursive===
<
data: lv_temp type i.
Line 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.
<
CARD i,res
Line 399 ⟶ 415:
FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Factorial.png Screenshot from Atari 8-bit computer]
Line 420 ⟶ 436:
=={{header|ActionScript}}==
===Iterative===
<
{
if (n < 0)
Line 430 ⟶ 446:
return fact;
}</
===Recursive===
<
{
if (n < 0)
Line 441 ⟶ 457:
return n * factorial(n - 1);
}</
=={{header|Ada}}==
===Iterative===
<
Result : Positive := N;
Counter : Natural := N - 1;
Line 453 ⟶ 469:
end loop;
return Result;
end Factorial;</
===Recursive===
<
Result : Positive := 1;
begin
Line 462 ⟶ 478:
end if;
return Result;
end Factorial;</
===Numerical Approximation===
<
with Ada.Numerics.Generic_Complex_Elementary_Functions;
with Ada.Numerics.Generic_Elementary_Functions;
Line 525 ⟶ 541:
New_Line;
end loop;
end Factorial_Numeric_Approximation;</
{{out}}
<pre>
Line 542 ⟶ 558:
=={{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 561 ⟶ 582:
return result;
}</
=={{header|ALGOL 60}}==
{{works with|A60}}
<
comment factorial - algol 60;
integer procedure factorial(n); integer n;
Line 578 ⟶ 599:
for i:=1 step 1 until 10 do outinteger(1,factorial(i));
outstring(1,"\n")
end</
{{out}}
<pre>
Line 586 ⟶ 607:
=={{header|ALGOL 68}}==
===Iterative===
<
LONG LONG INT z := 1;
FOR n TO upb n DO z *:= n OD;
z
); ~</
===Numerical Approximation===
Line 596 ⟶ 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 626 ⟶ 647:
OD
)
</syntaxhighlight>
{{out}}
<pre>
Line 642 ⟶ 663:
===Recursive===
<
CASE n+1 IN
1,1,2,6,24,120,720 # a brief lookup #
Line 648 ⟶ 669:
n*factorial(n-1)
ESAC
; ~</
=={{header|ALGOL W}}==
Iterative solution
<
% computes factorial n iteratively %
integer procedure factorial( integer value n ) ;
Line 666 ⟶ 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;
Line 676 ⟶ 697:
FACT := FACT * I;
FACTORIAL := FACT;
END;</
=={{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 710 ⟶ 731:
}
return ans;
}</
===Recursive===
<
if (n < 0){
System.debug('No negative numbers');
Line 718 ⟶ 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 739 ⟶ 767:
end repeat
return R
end factorial</
===Recursion===
Line 746 ⟶ 774:
(Perhaps because the iterative code is making use of list splats)
<
on factorial(x)
if x > 1 then
Line 753 ⟶ 781:
1
end if
end factorial</
===Fold===
Line 759 ⟶ 787:
where product is defined in terms of a fold.
<
-- factorial :: Int -> Int
Line 830 ⟶ 858:
foldl(multiply, 1, xs)
end product</
{{Out}}
<pre>39916800</pre>
=={{header|Arendelle}}==
Line 868 ⟶ 876:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 1,047 ⟶ 1,055:
</syntaxhighlight>
=={{header|ArnoldC}}==
<
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
Line 1,070 ⟶ 1,078:
CHILL
I'LL BE BACK product
HASTA LA VISTA, BABY</
=={{header|Arturo}}==
===Recursive===
<
if? n>0 [n * factorial n-1]
else [1]
]</
===Fold===
<
fold.seed:1 1..n [a,b][a*b]
]</
===Product===
<
loop 1..19 [x][
print ["Factorial of" x "=" factorial x]
]</
{{out}}
Line 1,118 ⟶ 1,126:
=={{header|AsciiDots}}==
<syntaxhighlight lang="asciidots">
/---------*--~-$#-&
| /--;---\| [!]-\
Line 1,126 ⟶ 1,134:
*-------+-</
\-#0----/
</syntaxhighlight>
=={{header|ATS}}==
===Iterative===
<syntaxhighlight lang="ats">
fun
fact
Line 1,142 ⟶ 1,150:
val () = while (n > 0) (res := res * n; n := n - 1)
}
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="ats">
fun
factorial
Line 1,151 ⟶ 1,159:
if n > 0 then n * factorial(n-1) else 1
// end of [factorial]
</syntaxhighlight>
===Tail-recursive===
<syntaxhighlight lang="ats">
fun
factorial
Line 1,163 ⟶ 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 1,175 ⟶ 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 1,198 ⟶ 1,219:
Next
Return $fact
EndFunc</
===Recursive===
<
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
Line 1,209 ⟶ 1,230:
EndIf
return $int * factorial($int - 1)
EndFunc</
=={{header|Avail}}==
Avail has a built-in factorial method using the standard exclamation point.
<
Its implementation is quite simple, using iterative <code>left fold_through_</code>.
<
Method "_`!" is
Line 1,223 ⟶ 1,244:
|
left fold 2 to n through [k : [2..∞), s : [2..∞) | k × s]
];</
=={{header|AWK}}==
'''Recursive'''
<
{
if ( n <= 1 ) return 1;
return n*fact_r(n-1);
}</
'''Iterative'''
<
{
if ( n < 1 ) return 1;
Line 1,242 ⟶ 1,263:
}
return r
}</
=={{header|Axe}}==
'''Iterative'''
<
1→R
For(I,1,r₁)
Line 1,252 ⟶ 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 1,271 ⟶ 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 1,284 ⟶ 1,305:
{1 }{ dup 1 - fact ! *})
cond}))
</syntaxhighlight>
When run, either code snippet generates the following
Line 1,300 ⟶ 1,321:
362880
3628800</pre>
=={{header|bash}}==
===Recursive===
<
{
if [ $1 -le 1 ]
Line 1,333 ⟶ 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 1,346 ⟶ 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 1,357 ⟶ 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}}===
Line 1,363 ⟶ 1,497:
====Iterative====
<
20 REM COMMODORE BASIC 2.0
30 INPUT "N=";N: GOSUB 100
Line 1,373 ⟶ 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
Line 1,394 ⟶ 1,526:
230 SP=SP-1: F(S(SP-1))=S(SP-1)*S(SP): REM MEMOIZE
240 S(SP-1)=F(S(SP-1)): REM PUSH(RESULT)
250 RETURN</
{{Out}}
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>
==={{header|GW-BASIC}}===
<
20 IF N < 0 THEN GOTO 10
30 F# = 1
Line 1,419 ⟶ 1,686:
50 F# = F# * N
60 N = N - 1
70 GOTO 40</
==={{header|IS-BASIC}}===
<
110 LET F=1
120 FOR I=2 TO N
Line 1,428 ⟶ 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,444 ⟶ 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,453 ⟶ 1,950:
80 LET N=N-1
90 GOSUB 60
100 RETURN</
{{in}}
<pre>13</pre>
{{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="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,506 ⟶ 2,301:
echo %y%
pause
exit</
=={{header|bc}}==
<
define f(x) {
Line 1,529 ⟶ 2,310:
}
f(1000)
quit</
=={{header|Beads}}==
<
// only works for cardinal numbers 0..N
calc main_init
Line 1,550 ⟶ 2,331:
return 1
else
return n * Recursive(n-1)</
{{out}}
<pre>24
Line 1,559 ⟶ 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,575 ⟶ 2,356:
<code>i</code> indicates that the program expects the user to enter an integer.
<
i0
1
Line 1,587 ⟶ 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}}==
<
! 720 ≡ Fac 6</
=={{header|Bracmat}}==
Compute 10! and checking that it is 3628800, the esoteric way
<
=
. !arg:0&1
Line 1,629 ⟶ 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,640 ⟶ 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,654 ⟶ 2,439:
Lastly, here is an iterative solution
<
r
. !arg:?r
Line 1,660 ⟶ 2,445:
' (!arg:>1&(!arg+-1:?arg)*!r:?r)
& !r
);</
factorial$5000
Line 1,667 ⟶ 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,681 ⟶ 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,690 ⟶ 2,487:
Following examples display other ways to calculate the factorial function:
<
blsq ) 1 6r@pd
720
Line 1,703 ⟶ 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,713 ⟶ 2,510:
return result;
}
</syntaxhighlight>
Handle negative n (returning -1)
<
int result = 1;
if(n<0)
Line 1,725 ⟶ 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,752 ⟶ 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,798 ⟶ 2,595:
19,"\n%04d") ):"%4d",l1-> lll[l] ) ; }
ll1ll(10); }
</syntaxhighlight>
=={{header|C sharp|C#}}==
===Iterative===
<
class Program
Line 1,823 ⟶ 2,620:
Console.WriteLine(Factorial(10));
}
}</
===Recursive===
<
class Program
Line 1,841 ⟶ 2,638:
Console.WriteLine(Factorial(10));
}
}</
===Tail Recursive===
<
class Program
Line 1,869 ⟶ 2,666:
Console.WriteLine(Factorial(10));
}
}</
===Functional===
<
using System.Linq;
Line 1,885 ⟶ 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,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 1,908 ⟶ 2,729:
Console.WriteLine(Factorial(250));
}
}</
{{out}}
<pre>3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000</pre>
Line 1,914 ⟶ 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,921 ⟶ 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 while loop.
<
long long int factorial(long long int n)
{
Line 1,932 ⟶ 2,753:
r *= n--;
return r;
}</
===Template===
<
struct Factorial
{
Line 1,953 ⟶ 2,774:
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}</
===Compare all Solutions (except the meta)===
<
#include <chrono>
#include <iostream>
Line 2,062 ⟶ 2,883:
std::cout << "std::accumulate lambda(6) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
}
}</
<pre>do-while(1) result 2432902008176640000 took 0.110000 µs
while(2) result 2432902008176640000 took 0.078000 µs
Line 2,073 ⟶ 2,894:
=={{header|C3}}==
=== Iterative ===
<
{
int result = 1;
Line 2,082 ⟶ 2,903:
return result;
}
</syntaxhighlight>
=== Recursive ===
<
{
return n == 0 ? 1 : n * factorial(n - 1);
}
</syntaxhighlight>
=== Recursive macro ===
In this case the value of x is compiled to a constant.
<
{
$if ($n == 0):
Line 2,105 ⟶ 2,926:
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 2,133 ⟶ 2,954:
}
}
</syntaxhighlight>
=={{header|Chapel}}==
<
var r = 1;
for i in 1..n do
Line 2,142 ⟶ 2,963:
return r;
}</
=={{header|Chef}}==
<
Only reads one value.
Line 2,161 ⟶ 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 2,189 ⟶ 3,010:
// test
if ( answer == 120 ) <<<"success">>>;
</syntaxhighlight>
===Iterative===
<syntaxhighlight lang="text">
1 => int total;
fun int factorial(int i)
Line 2,203 ⟶ 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 2,220 ⟶ 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 2,242 ⟶ 3,063:
println(factorialStatic(static 5)); // 120
println(factorial(Int64(20))); // 2432902008176640000
}</
=={{header|Clio}}==
=== Recursive ===
<
fn factorial n:
if n <= 1: n
Line 2,254 ⟶ 3,075:
10 -> factorial -> print
</syntaxhighlight>
=={{header|CLIPS}}==
<
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
Line 2,264 ⟶ 3,085:
1
else
(* ?a (factorial (- ?a 1))))))</
=={{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}}==
<
if n<0 then signal negative
elseif n=0 then return(1)
Line 2,301 ⟶ 3,130:
stream$putl(po, int$unparse(i) || "! = " || int$unparse(fac))
end
end start_up</
{{out}}
<pre>0! = 1
Line 2,316 ⟶ 3,145:
=={{header|CMake}}==
<
set(product 1)
foreach(i RANGE 2 ${n})
Line 2,325 ⟶ 3,154:
factorial(f 12)
message("12! = ${f}")</
=={{header|COBOL}}==
Line 2,332 ⟶ 3,161:
=== Intrinsic Function ===
COBOL includes an intrinsic function which returns the factorial of its argument.
<
=== Iterative ===
{{works with|GnuCOBOL}}
<
FUNCTION-ID. factorial_iterative.
Line 2,357 ⟶ 3,186:
END FUNCTION factorial_iterative.
</syntaxhighlight>
=== Recursive ===
{{works with|Visual COBOL}}
{{works with|GnuCOBOL}}
<
FUNCTION-ID. factorial_recursive.
Line 2,384 ⟶ 3,213:
END FUNCTION factorial_recursive.
</syntaxhighlight>
=== Test ===
{{works with|GnuCOBOL}}
<
PROGRAM-ID. factorial_test.
Line 2,422 ⟶ 3,251:
END PROGRAM factorial_test.
</syntaxhighlight>
{{out}}
Line 2,436 ⟶ 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 2,455 ⟶ 3,284:
ENDIF
RETURN r
ENDPROC Recursive</
=={{header|Comefrom0x10}}==
Line 2,461 ⟶ 3,290:
This is iterative; recursion is not possible in Comefrom0x10.
<
acc = 1
Line 2,475 ⟶ 3,304:
n = n - 1
acc # prints the result</
=={{header|Common Lisp}}==
Recursive:
<
(if (zerop n) 1 (* n (factorial (1- n)))))</
or
<
(if (< n 2) 1 (* n (factorial (1- n)))))</
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===
{{Works with|Allegro CL|10.1}}
<
(defun factorial (n)
Line 2,511 ⟶ 3,340:
(t (* n (factorial (- n 1))))))
(format t "~a" "factorial of 8: ")
(factorial 8)</
Output:
<pre>factorial of 8: 40320</pre>
Line 2,518 ⟶ 3,347:
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 2,560 ⟶ 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 2,578 ⟶ 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===
<
ans = 1
(1..x).each do |i|
Line 2,588 ⟶ 3,426:
end
return ans
end</
===Recursive===
<
if x <= 1
return 1
end
return x * factorial(x - 1)
end</
=={{header|D}}==
===Iterative Version===
<
in {
assert(n <= 12);
Line 2,618 ⟶ 3,456:
// Computed and printed at run-time.
12.factorial.writeln;
}</
{{out}}
<pre>479001600u
Line 2,624 ⟶ 3,462:
===Recursive Version===
<
in {
assert(n <= 12);
Line 2,642 ⟶ 3,480:
// Computed and printed at run-time.
12.factorial.writeln;
}</
(Same output.)
===Functional Version===
<
uint factorial(in uint n) pure nothrow @nogc
Line 2,661 ⟶ 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 2,686 ⟶ 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 2,701 ⟶ 3,539:
print(fact(10));
print(fact(-1));
}</
===Iterative===
<
if(n<0) {
throw new IllegalArgumentException('Argument less than 0');
Line 2,717 ⟶ 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,739 ⟶ 3,577:
* For example, print the factorial of 50.
*]sz
50 lfx psz</
=={{header|Delphi}}==
===Iterative===
<
{$APPTYPE CONSOLE}
Line 2,758 ⟶ 3,596:
begin
Writeln('5! = ', FactorialIterative(5));
end.</
===Recursive===
<
{$APPTYPE CONSOLE}
Line 2,775 ⟶ 3,613:
begin
Writeln('5! = ', FactorialRecursive(5));
end.</
===Tail Recursive===
<
{$APPTYPE CONSOLE}
Line 2,801 ⟶ 3,639:
begin
Writeln('5! = ', FactorialTailRecursive(5));
end.</
=={{header|Draco}}==
<
* supported value. This is why the input parameter
* is a byte. The parameters are all unsigned. */
Line 2,822 ⟶ 3,660:
writeln(i:2, "! = ", fac(i):9)
od
corp</
{{out}}
<pre> 0! = 1
Line 2,839 ⟶ 3,677:
=={{header|Dragon}}==
<syntaxhighlight lang="text">select "std"
factorial = 1
n = readln()
Line 2,847 ⟶ 3,685:
}
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,859 ⟶ 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,876 ⟶ 3,714:
n * factorial(n - 1)
}
}</
=={{header|Dylan}}==
Line 2,882 ⟶ 3,720:
=== Functional ===
<
define method factorial (n)
if (n < 1)
Line 2,890 ⟶ 3,728:
end
end method;
</syntaxhighlight>
=== Iterative ===
<
define method factorial (n)
if (n < 1)
Line 2,906 ⟶ 3,744:
end
end method;
</syntaxhighlight>
=== Recursive ===
<
define method factorial (n)
if (n < 1)
Line 2,924 ⟶ 3,762:
loop(n)
end method;
</syntaxhighlight>
=== Tail recursive ===
<
define method factorial (n)
if (n < 1)
Line 2,945 ⟶ 3,783:
loop(n, n)
end method;
</syntaxhighlight>
=={{header|Déjà Vu}}==
===Iterative===
<
1
while over:
* over
swap -- swap
drop swap</
===Recursive===
<
if dup:
* factorial -- dup
else:
1 drop</
=={{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,997 ⟶ 3,835:
(fact 10)
→ 3628800
</syntaxhighlight>
===Tail recursive===
<
(define (fact n (acc 1))
(if (zero? n) acc
Line 3,005 ⟶ 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 3,033 ⟶ 3,994:
return (ans);
end
</syntaxhighlight>
===Recursive===
<syntaxhighlight lang="egl">
function fact(n int in) returns (bigint)
if (n < 0)
Line 3,047 ⟶ 4,008:
end
end
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
note
description: "recursive and iterative factorial example of a positive integer."
Line 3,101 ⟶ 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 3,135 ⟶ 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 3,157 ⟶ 4,118:
factorial a =
factorialAux a 1
</syntaxhighlight>
===
<
import List exposing (product, range)
Line 3,167 ⟶ 4,128:
factorial a =
product (range 1 a)
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<
;; Functional (most elegant and best suited to Lisp dialects):
(defun fact (n)
Line 3,182 ⟶ 4,143:
;; (For N = 0, number-sequence returns the empty list, resp. nil,
;; and the * function works with zero arguments, returning 1.)
</syntaxhighlight>
<
;; Recursive:
(defun fact (n)
Line 3,193 ⟶ 4,154:
((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 ===
<
long result = 1;
do {
Line 3,211 ⟶ 4,214:
while(--n);
return result;
}</
=={{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 3,230 ⟶ 4,233:
'''Iterative procedure:'''
<syntaxhighlight lang="erre">
PROCEDURE FACTORIAL(X%->F)
F=1
Line 3,239 ⟶ 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 3,253 ⟶ 4,256:
Straight forward methods
===Iterative===
<
atom f = 1
while n > 1 do
Line 3,261 ⟶ 4,264:
return f
end function</
===Recursive===
<
if n > 1 then
return factorial(n-1) * n
Line 3,270 ⟶ 4,273:
return 1
end if
end function</
===Tail Recursive===
{{works with|Euphoria|4.0.0}}
<
if n <= 0 then
return acc
Line 3,280 ⟶ 4,283:
return factorial(n-1, n*acc)
end if
end function</
==='Paper tape' / Virtual Machine version===
Line 3,286 ⟶ 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 3,391 ⟶ 4,394:
end if
ip += 1
end while</
=={{header|Excel}}==
Line 3,397 ⟶ 4,400:
Choose a cell and write in the function bar on the top :
<
=fact(5)
</syntaxhighlight>
The result is shown as :
Line 3,409 ⟶ 4,412:
=={{header|Ezhil}}==
Recursive
<
நிரல்பாகம் fact ( n )
@( n == 0 ) ஆனால்
Line 3,419 ⟶ 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 3,437 ⟶ 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 3,459 ⟶ 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 3,498 ⟶ 4,501:
echo (factorialFunctional(20))
}
}</
=={{header|Fermat}}==
The factorial function is built in.
<syntaxhighlight lang
{{out}}<pre>
10106320568407814933908227081298764517575823983241454113404208073574138021 `
Line 3,527 ⟶ 4,530:
=={{header|FOCAL}}==
<
1.2 S N=-3; D 2
1.3 S N=100; D 2
Line 3,541 ⟶ 4,544:
3.1 T "N IS NEGATIVE" !; D 2.9
4.1 T "FACTORIAL OF 0 IS 1" !; D 2.9</
{{output}}
<pre>
Line 3,563 ⟶ 4,566:
=={{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 3,580 ⟶ 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:
<
INTEGER, INTENT(IN) :: X
Line 3,597 ⟶ 4,600:
END IF
END FUNCTION RECURSIVE_FACTORIAL</
===FORTRAN 77===
<
INTEGER N,I,FACT
FACT=1
Line 3,610 ⟶ 4,613:
MFACT = FACT
RETURN
END</
=={{header|friendly interactive shell}}==
Line 3,656 ⟶ 4,619:
===Iterative===
<
function factorial
set x $argv[1]
Line 3,665 ⟶ 4,628:
echo $result
end
</syntaxhighlight>
===Recursive===
<
function factorial
set x $argv[1]
Line 3,677 ⟶ 4,640:
end
end
</syntaxhighlight>
=={{header|Frink}}==
Line 3,688 ⟶ 4,651:
* 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.
<
// Calculate factorial with math operator
x = 5
Line 3,695 ⟶ 4,658:
// Calculate factorial with built-in function
println[factorial[x]]
</syntaxhighlight>
Building a factorial function with no recursion
<
// 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
<
factorial3[x] :=
{
Line 3,713 ⟶ 4,676:
println[factorial3[5]]
</syntaxhighlight>
=={{header|FunL}}==
=== Procedural ===
<
if n < 0
error( 'factorial: n should be non-negative' )
Line 3,726 ⟶ 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 3,743 ⟶ 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 3,755 ⟶ 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}}==
<syntaxhighlight lang
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}}==
<
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 3,936 ⟶ 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 3,962 ⟶ 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,979 ⟶ 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,999 ⟶ 4,915:
}
fmt.Println(100, factorial(100))
}</
{{out}}
<pre>
Line 4,016 ⟶ 4,932:
</pre>
===Built in, Lgamma===
<
import (
Line 4,041 ⟶ 4,957:
fmt.Println(100, factorial(100))
fmt.Println(800, factorial(800))
}</
{{out}}
<pre>
Line 4,061 ⟶ 4,977:
=={{header|Golfscript}}==
'''Iterative''' (uses folding)
<
5fact puts # test</
or
<
'''Recursive'''
<
=={{header|Gridscript}}==
<
#FACTORIAL.
Line 4,085 ⟶ 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 4,113 ⟶ 5,029:
factList.each { printf ' %3d', it }
println()
}</
{{out}}
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}}==
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
Line 4,155 ⟶ 5,095:
main = do
print (5 !)
print ((4 !) !)</
=== Binary splitting ===
The following method is more efficient for large numbers.
<
productFromTo a b =
if a>b then 1
Line 4,167 ⟶ 5,107:
where c = (a+b) `div` 2
factorial = productFromTo 1</
=={{header|Haxe}}==
===Iterative===
<
var result = 1;
while (1<n)
result *= n--;
return result;
}</
===Recursive===
<
return n == 0 ? 1 : n * factorial2(n - 1);
}</
===Tail-Recursive===
<
return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
Line 4,190 ⟶ 5,130:
static function factorial(n:Int):Int {
return _fac_aux(n,1);
}</
===Functional===
<
return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);
}</
===Comparison===
<
using Lambda;
Line 4,255 ⟶ 5,195:
Sys.println('functional'.rpad(' ', 20) + 'result: $result time: $duration ms');
}
}</
{{out}}
Line 4,267 ⟶ 5,207:
=={{header|hexiscript}}==
===Iterative===
<
let acc 1
while n > 0
Line 4,273 ⟶ 5,213:
endwhile
return acc
endfun</
===Recursive===
<
if n <= 0
return 1
Line 4,281 ⟶ 5,221:
return n * fac (n - 1)
endif
endfun</
=={{header|HicEst}}==
<
FUNCTION factorial(n)
Line 4,291 ⟶ 5,231:
factorial = factorial * i
ENDDO
END</
=={{header|HolyC}}==
=== Iterative ===
<
U64 i, result = 1;
for (i = 1; i <= n; ++i)
Line 4,303 ⟶ 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 4,318 ⟶ 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 4,327 ⟶ 5,267:
(print (! 6)) ; 720
(print (! 0)) ; 1</
=={{header|i}}==
<
return n!
}
Line 4,342 ⟶ 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 4,360 ⟶ 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====
<
(defn factorial [x]
(cond
Line 4,408 ⟶ 5,388:
(= x 0) 1
(* x (factorial (dec x)))))
</syntaxhighlight>
====Tail Recursive====
Line 4,414 ⟶ 5,394:
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.
<
(defn factorial-iter [product counter max-count]
(if (> counter max-count)
Line 4,422 ⟶ 5,402:
(defn factorial [n]
(factorial-iter 1 1 n))
</syntaxhighlight>
===Iterative===
<
(defn factorial [x]
(cond
Line 4,435 ⟶ 5,415:
(*= fac i))
fac)))
</syntaxhighlight>
===Functional===
<
(defn factorial [x]
(cond
Line 4,444 ⟶ 5,424:
(= x 0) 1
(product (range 1 (inc x)))))
</syntaxhighlight>
=={{header|Java}}==
===Iterative===
<
package programas;
Line 4,503 ⟶ 5,483:
}
</syntaxhighlight>
===Recursive===
<
package programas;
Line 4,564 ⟶ 5,544:
}
</syntaxhighlight>
===Simplified and Combined Version===
<
import java.math.BigInteger;
import java.util.InputMismatchException;
Line 4,605 ⟶ 5,585:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 4,611 ⟶ 5,591:
===Iterative===
<
//check our edge case
if (n < 0) { throw "Number must be non-negative"; }
Line 4,622 ⟶ 5,602:
}
return result;
}</
===Recursive===
Line 4,628 ⟶ 5,608:
====ES5 (memoized )====
<
var memo = {};
Line 4,638 ⟶ 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 4,672 ⟶ 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 4,711 ⟶ 5,691:
// MAIN ------
return test();
})();</
{{Out}}
<pre>6402373705728000</pre>
Line 4,719 ⟶ 5,699:
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>
Line 4,768 ⟶ 5,748:
}
</script></
=={{header|JOVIAL}}==
<
BEGIN
ITEM ARG U;
Line 4,779 ⟶ 5,759:
TEMP = TEMP*I;
FACTORIAL = TEMP;
END</
=={{header|Joy}}==
<
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 4,800 ⟶ 5,780:
end;
# Extract the accumulated value from the output of _fact:
[1, .] | _fact | .[0] ;</
=={{header|Jsish}}==
<
/* recursive */
Line 4,824 ⟶ 5,804:
;factorial(42);
try { factorial(-1); } catch (err) { puts(err); }
}</
{{out}}
Line 4,862 ⟶ 5,842:
'''Dynamic version''':
<
n < 0 && return zero(n)
f = one(n)
Line 4,873 ⟶ 5,853:
for i in 10:20
println("$i -> ", fact(i))
end</
{{out}}
Line 4,889 ⟶ 5,869:
'''Alternative version''':
<
@show fact2(20)</
{{out}}
<pre>fact2(20) = 2432902008176640000</pre>
Line 4,896 ⟶ 5,876:
=={{header|K}}==
===Iterative===
<
facti 5
120</
===Recursive===
<
factr 6
720</
=={{header|Klingphix}}==
<
:factorial
dup 1 great (
Line 4,922 ⟶ 5,902:
] for
" " input</
{{out}}
<pre>Factorial(0) = 1
Line 4,950 ⟶ 5,930:
=={{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 4,968 ⟶ 5,948:
}
return ret;
}</
=={{header|Kotlin}}==
<
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
Line 4,990 ⟶ 5,970:
println("$n! = " + facti(n))
println("$n! = " + factr(n))
}</
{{Out}}
<pre>20! = 2432902008176640000
Line 4,996 ⟶ 5,976:
=={{header|Lambdatalk}}==
<
{def fac
{lambda {:n}
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>
=={{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">
writeln factorial(7)
</syntaxhighlight>
=== Recursive ===
<syntaxhighlight lang="langur">
writeln factorial(7)
</syntaxhighlight>
=== Iterative ===
<syntaxhighlight lang
val factorial = fn(i) {
for x in 2 .
answer *= x
}
}
writeln factorial(7)
</syntaxhighlight>
=== Iterative Folding ===
<syntaxhighlight lang="langur">
writeln
</syntaxhighlight>
{{out}}
Line 5,058 ⟶ 6,087:
=={{header|Lasso}}==
===Iterative===
<
local(x = 1)
with i in generateSeries(2, #n)
Line 5,065 ⟶ 6,094:
}
return #x
}</
===Recursive===
<
=={{header|Latitude}}==
===Functional===
<
1 upto ($1 + 1) product.
}.</
===Recursive===
<
takes '[n].
if { n == 0. } then {
Line 5,085 ⟶ 6,114:
n * factorial (n - 1).
}.
}.</
===Iterative===
<
local 'acc = 1.
1 upto ($1 + 1) do {
Line 5,094 ⟶ 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 5,103 ⟶ 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 5,136 ⟶ 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 5,152 ⟶ 6,219:
121645100408832000
2432902008176640000)
</syntaxhighlight>
Or, using <tt>io:format</tt> to print results to <tt>stdout</tt>:
<
> (lists:foreach
(lambda (x)
Line 5,172 ⟶ 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 5,221 ⟶ 6,257:
end repeat
return res
end</
=={{header|Lisaac}}==
<
+ result : INTEGER;
(x <= 1).if {
Line 5,232 ⟶ 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
Line 5,274 ⟶ 6,310:
one DAT 1 // constant 1
// end
</syntaxhighlight>
=={{header|LiveCode}}==
<
function factorialr n
if n < 2 then
Line 5,302 ⟶ 6,338:
// iterative
function factorialit n
if n > 1 then
repeat with i = 1 to n
Line 5,309 ⟶ 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 5,391 ⟶ 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 5,398 ⟶ 6,434:
===Recursive===
<
if :n < 2 [output 1]
output :n * factorial :n-1
end</
===Iterative===
Line 5,407 ⟶ 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 5,430 ⟶ 6,466:
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR Loop
KTHXBYE</
{{Out}}
<pre>0! = 1
Line 5,448 ⟶ 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 5,458 ⟶ 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 5,464 ⟶ 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 5,470 ⟶ 6,506:
return t[n]
end
})</
=={{header|M2000 Interpreter}}==
Line 5,481 ⟶ 6,517:
1@ is 1 in Decimal type (27 digits).
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Locale 1033 ' ensure #,### print with comma
Line 5,504 ⟶ 6,540:
}
Checkit
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 5,537 ⟶ 6,573:
=={{header|M4}}==
<
dnl
factorial(5)</
{{out}}
Line 5,548 ⟶ 6,584:
=={{header|MAD}}==
<
R CALCULATE FACTORIAL OF N
Line 5,564 ⟶ 6,600:
PRNFAC PRINT FORMAT FMT, NUM, FACT.(NUM)
END OF PROGRAM</
{{out}}
Line 5,586 ⟶ 6,622:
Recursive version, MANOOLish “cascading” notation:
<syntaxhighlight lang="manool">
{ let rec
{ Fact = -- compile-time constant binding
Line 5,597 ⟶ 6,633:
Fact
}
</syntaxhighlight>
Conventional notation (equivalent to the above up to AST):
<syntaxhighlight lang="manool">
{ let rec
{ Fact = -- compile-time constant binding
Line 5,612 ⟶ 6,648:
Fact
}
</syntaxhighlight>
Iterative version (in MANOOL, probably more appropriate in this particular case):
<syntaxhighlight lang="manool">
{ let
{ Fact = -- compile-time constant binding
Line 5,628 ⟶ 6,664:
Fact
}
</syntaxhighlight>
=={{header|Maple}}==
Builtin
<syntaxhighlight lang="maple">
> 5!;
120
</syntaxhighlight>
Recursive
<
if n = 0 or n = 1 then
1
Line 5,644 ⟶ 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 5,687 ⟶ 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 5,713 ⟶ 6,749:
red 11 ! .
</syntaxhighlight>
=={{header|Maxima}}==
=== Built-in ===
<syntaxhighlight lang
=== Recursive ===
<
=== Iterative===
<
=={{header|MAXScript}}==
=== Iterative ===
<
(
if n == 0 then return 1
Line 5,734 ⟶ 6,770:
)
fac
)</
=== Recursive ===
<
(
local fac = 1
Line 5,744 ⟶ 6,780:
)
fac
)</
=={{header|Mercury}}==
=== Recursive (using arbitrary large integers and memoisation) ===
<
:- interface.
Line 5,763 ⟶ 6,799:
-> integer(1)
; factorial(N - integer(1)) * N
).</
A small test program:
<
:- interface.
:- import_module io.
Line 5,783 ⟶ 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|min}}==
{{works with|min|0.19.6}}
<
=={{header|MiniScript}}==
=== Iterative ===
<
result = 1
for i in range(2,n)
Line 5,816 ⟶ 6,838:
end function
print factorial(10)</
=== Recursive ===
<
if n <= 0 then return 1 else return n * factorial(n-1)
end function
print factorial(10)</
{{out}}
<pre>3628800</pre>
=={{header|MiniZinc}}==
<
let {
array[0..n] of var int: factorial;
Line 5,840 ⟶ 6,862:
var int: fac = factorial(6);
solve satisfy;
output [show(fac),"\n"];</
=={{header|MIPS Assembly}}==
=== Iterative ===
<
##################################
# Factorial; iterative #
Line 5,892 ⟶ 6,914:
li $v0, 10 #set syscall arg to EXIT
syscall #make the syscall
</syntaxhighlight>
=== Recursive ===
<
#reference code
#int factorialRec(int n){
Line 5,937 ⟶ 6,959:
mul $v0, $a0, $v0
jr $ra
</syntaxhighlight>
=={{header|Mirah}}==
<
2.upto(n-1) do |i|
n *= i
Line 5,947 ⟶ 6,969:
end
puts factorial_iterative 10</
=={{header|МК-61/52}}==
Line 5,956 ⟶ 6,978:
=={{header|ML/I}}==
===Iterative===
<
"" Factorial - iterative
MCSKIP MT,<>
Line 5,972 ⟶ 6,994:
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4)</
===Recursive===
<
"" Factorial - recursive
MCSKIP MT,<>
Line 5,986 ⟶ 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 6,014 ⟶ 7,036:
ReadChar
END Factorial.</
=={{header|Modula-3}}==
===Iterative===
<
VAR
result := n;
Line 6,028 ⟶ 7,050:
END;
RETURN result;
END FactIter;</
===Recursive===
<
VAR result := 1;
Line 6,038 ⟶ 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 6,054 ⟶ 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 6,069 ⟶ 7,103:
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative number
Write $$factorial(3.7) ; Not an integer</
=={{header|MyrtleScript}}==
<
int factorial = a
repeat int i = (a - 1) : i == 0 : i-- {
Line 6,078 ⟶ 7,112:
}
return factorial
}</
=={{header|Nanoquery}}==
{{trans|Python}}
<
result = 1
for i in range(1, n)
Line 6,088 ⟶ 7,122:
end
return result
end</
=={{header|Neko}}==
<
var i = 1;
var result = 1;
Line 6,103 ⟶ 7,137:
};
$print(factorial(10));</
=={{header|Nemerle}}==
Line 6,109 ⟶ 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 6,143 ⟶ 7,177:
accumulator //implicit return
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 6,196 ⟶ 7,230:
fact = 1
return fact</
{{out}}
<pre>
Line 6,206 ⟶ 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.
<
{{out}}
<pre>prompt$ nickle
Line 6,241 ⟶ 7,275:
=={{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|Nu}}==
<syntaxhighlight lang="nu">
def 'math factorial' [] {[$in 1] | math max | 1..$in | math product}
..10 | each {math factorial}
</syntaxhighlight>
{{out}}
<pre>
╭────┬─────────╮
│ 0 │ 1 │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 6 │
│ 4 │ 24 │
│ 5 │ 120 │
│ 6 │ 720 │
│ 7 │ 5040 │
│ 8 │ 40320 │
│ 9 │ 362880 │
│ 10 │ 3628800 │
╰────┴─────────╯
</pre>
=={{header|Nyquist}}==
===Lisp Syntax===
Iterative:
<
(do ((x n (* x n)))
((= n 1) x)
(setq n (1- n))))</
Recursive:
<
(if (= n 1)
1
(* n (factorial (1- n)))))</
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="modula2">
MODULE Factorial;
IMPORT
Line 6,320 ⟶ 7,377:
END
END Factorial.
</syntaxhighlight>
{{Out}}
<pre>
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>
=={{header|Objeck}}==
===Iterative===
<
class Fact {
function : Main(args : String[]) ~ Nil {
Line 6,354 ⟶ 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 6,381 ⟶ 7,508:
The following code uses the Zarith package to calculate the factorials of larger numbers:
<
let rec loop acc = function
| 0 -> acc
Line 6,392 ⟶ 7,519:
Sys.argv.(1) |> int_of_string |> factorial |> Z.print;
print_newline ()
end</
{{out}}
Line 6,400 ⟶ 7,527:
=={{header|Octave}}==
<
printf("%d\n", factorial(50));
Line 6,422 ⟶ 7,549:
endfunction
printf("%d\n", iter_fact(50));</
{{out}}
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}}==
Recursive :
<
Imperative :
<
{{out}}
Line 6,453 ⟶ 7,598:
=={{header|Order}}==
Simple recursion:
<
#define ORDER_PP_DEF_8fac \
Line 6,461 ⟶ 7,606:
8mul(8N, 8fac(8dec(8N))))))
ORDER_PP(8to_lit(8fac(8))) // 40320</
Tail recursion:
<
#define ORDER_PP_DEF_8fac \
Line 6,473 ⟶ 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 6,490 ⟶ 7,635:
in
{Loop N 1}
end</
=== Iterative ===
<
Result = {NewCell 1}
in
Line 6,499 ⟶ 7,644:
end
@Result
end</
=={{header|Panda}}==
<
product{{1..n}}
1..10.fac
</syntaxhighlight>
=={{header|PARI/GP}}==
Line 6,512 ⟶ 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 6,534 ⟶ 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 6,548 ⟶ 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 6,556 ⟶ 7,701:
);
v[n+1]
};</
=={{header|Pascal}}==
=== Iterative ===
<
var
i, result: integer;
Line 6,568 ⟶ 7,713:
result := result * i;
factorial := result
end;</
=== Iterative FreePascal ===
<syntaxhighlight lang="pascal">
{$mode objFPC}{R+}
FUNCTION Factorial ( n : qword ) : qword;
Line 6,602 ⟶ 7,747:
Result := F ;
END;</
JPD 2021/03/24
=== using FreePascal with GMP lib===
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM EXBigFac ;
Line 6,700 ⟶ 7,845:
Digits: 156
93326215443944...00000000000000
</
=== Recursive ===
<
begin
if n = 0
Line 6,710 ⟶ 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 6,737 ⟶ 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|Peylang}}==
<
-- calculate factorial
Line 6,778 ⟶ 7,994:
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.
<!--<
<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>
Line 6,792 ⟶ 8,008:
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function
<!--</
The compiler knows where to find that for you, so a runnable program is just
<!--<
<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>
<!--</
{{out}}
<pre>
Line 6,805 ⟶ 8,021:
{{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.
<!--<
<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>
Line 6,832 ⟶ 8,048:
<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>
<!--</
{{out}}
<pre>
Line 6,862 ⟶ 8,078:
=={{header|Phixmonti}}==
<
def factorial
dup 1 > if
Line 6,878 ⟶ 8,094:
0 22 2 tolist for
"Factorial(" print dup print ") = " print factorial2 print nl
endfor</
=={{header|PHP}}==
=== Iterative ===
<
function factorial($n) {
if ($n < 0) {
Line 6,895 ⟶ 8,111:
return $factorial;
}
?></
=== Recursive ===
<
function factorial($n) {
if ($n < 0) {
Line 6,911 ⟶ 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}}==
<
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 6,943 ⟶ 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 6,979 ⟶ 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!.
<
To run:
Line 7,009 ⟶ 8,225:
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.</
=={{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 7,023 ⟶ 8,264:
end;
return (F);
end factorial;</
=={{header|PL/SQL}}==
<
Declare
/*====================================================================================================
Line 7,064 ⟶ 8,304:
End loop;
END;
</syntaxhighlight>
{{out}}
<pre>
Line 7,175 ⟶ 8,415:
=={{header|PostScript}}==
===Recursive===
<
dup 0 eq % check for the argument being 0
{
Line 7,186 ⟶ 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 7,234 ⟶ 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===
<
int fact(int n){
if(n <= 1){
Line 7,255 ⟶ 8,476:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 7,261 ⟶ 8,482:
</pre>
===Iterative===
<
long fi(int n) {
if (n < 0){
Line 7,279 ⟶ 8,500:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 7,289 ⟶ 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 7,299 ⟶ 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 7,315 ⟶ 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 7,329 ⟶ 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 7,345 ⟶ 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 7,401 ⟶ 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 7,416 ⟶ 8,619:
print(factorials(5))
# -> [1, 1, 2, 6, 24, 120]</
or
<
def factorial(n):
return prod(range(1, n + 1), dtype=int)</
===Recursive===
<
z=1
if n>1:
z=n*factorial(n-1)
return z</
{{out}}
Line 7,444 ⟶ 8,647:
or
<
return n * factorial(n - 1) if n else 1</
===Numerical Approximation===
Line 7,451 ⟶ 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 7,477 ⟶ 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 7,496 ⟶ 8,699:
===Iterative===
====Point-free====
<syntaxhighlight lang
or
<syntaxhighlight lang
or
<syntaxhighlight lang
====As a function====
<
===Recursive===
<
=={{header|Quackery}}==
===Iterative===
<
===Overly Complicated and Inefficient===
Line 7,580 ⟶ 8,719:
The On-Line Encyclopedia of Integer Sequences® [https://oeis.org].
<
[ odd not ] is even ( n --> b )
Line 7,622 ⟶ 8,761:
[ 1+ [A000142] -1 peek ] is !
</syntaxhighlight>
=={{header|R}}==
=== Recursive ===
<
if (n <= 1) 1
else n * Recall(n - 1)
}</
===Iterative===
<
f = 1
if (n > 1) {
Line 7,638 ⟶ 8,777:
}
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))
<
(for/fold ([pro 1]) ([i (in-range 1 (+ n 1))]) (* pro i)))</
Or quite simpler by an for/product
<
(for/product ([i (in-range 1 (+ n 1))]) i))</
=={{header|Raku}}==
Line 7,677 ⟶ 8,816:
<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"
say 5!;</
{{out}}<pre>120</pre>
Line 7,684 ⟶ 8,823:
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"
say fact[5]</
{{out}}<pre>120</pre>
=={{header|Rapira}}==
=== Iterative ===
<
f := 1
для i от 1 до n
Line 7,696 ⟶ 8,835:
кц
Возврат f
Кон Фун</
=== Recursive ===
<
Если n = 1
Возврат 1
Line 7,711 ⟶ 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 7,733 ⟶ 8,881:
===Recursive===
<
if(n>1) return n*factorial_rec(n-1);
else return 1;
}</
{{out}}
<pre>rascal>factorial_rec(10)
Line 7,742 ⟶ 8,890:
=={{header|RASEL}}==
<syntaxhighlight lang="text">1&$:?v:1-3\$/1\
>$11\/.@</
=={{header|REBOL}}==
<
Title: "Factorial"
URL: http://rosettacode.org/wiki/Factorial_function
Line 7,800 ⟶ 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 7,817 ⟶ 8,965:
=={{header|Red}}==
Iterative (variants):
<
fac: function [n][repeat i also n n: 1 [n: n * i] n]</
Recursive (variants):
<
fac: func [n][any [if n = 0 [1] n * fac n - 1]]
fac: func [n][do pick [[n * fac n - 1] 1] n > 1]</
Memoized:
<
=={{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
Line 7,838 ⟶ 9,014:
end if
end function
</syntaxhighlight>
=={{header|Retro}}==
A recursive implementation from the benchmarking code.
<
: factorial dup 0 = [ 1+ ] [ <factorial> ] if ;</
=={{header|REXX}}==
Line 7,850 ⟶ 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 7,867 ⟶ 9,043:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error***'; say; say arg(1); say; exit 13</
{{out|output|text= when using the input of: <tt> 100 </tt>}}
<pre>
Line 7,906 ⟶ 9,082:
╚═══════════════════════════════════════════════════════════════════════════╝
</pre>
<
/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/
numeric digits 99 /*99 digits initially, then expanded. */
Line 7,927 ⟶ 9,103:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; exit 13</
{{out|output|text= when using the input of: <tt> 1000 </tt>}}
<pre>
Line 7,949 ⟶ 9,125:
<br>is a multiple of five [or some other method], strip the trailing zeroes, and then convert it back to binary ── although it
<br>wouldn't be necessary to convert to/from base ten for checking for trailing zeros (in decimal).
<
numeric digits 200 /*start with two hundred digits. */
parse arg N . /*obtain an optional argument from CL. */
Line 7,975 ⟶ 9,151:
say N'! is ['length(!) " digits with " z ' trailing zeroes]:'
say /*display blank line (for whitespace).*/
say ! /*display the factorial product. */</
<!-- The word ''gooder'' is a humorous use of the non-word. -->
{{out|output|text= when using the input of: <tt> 100 </tt>}}
Line 8,047 ⟶ 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 8,055 ⟶ 9,265:
func fact nr if nr = 1 return 1 else return nr * fact(nr-1) ok
</syntaxhighlight>
=={{header|Robotic}}==
===Iterative===
<
input string "Enter a number:"
set "in" to "('ABS('input')')"
Line 8,075 ⟶ 9,285:
* "1"
end
</syntaxhighlight>
=={{header|Rockstar}}==
Here's the "minimized" Rockstar:
<syntaxhighlight lang="rockstar">
Factorial takes a number
If a number is 0
Line 8,087 ⟶ 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 8,100 ⟶ 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 8,107 ⟶ 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 8,145 ⟶ 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 8,157 ⟶ 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 8,199 ⟶ 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 8,230 ⟶ 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 8,236 ⟶ 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 8,285 ⟶ 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 8,324 ⟶ 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,330 ⟶ 9,628:
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 8,362 ⟶ 9,660:
To avoid this limitations the functions below use [http://seed7.sourceforge.net/libraries/bigint.htm bigInteger]:
===Iterative===
<
result
var bigInteger: fact is 1_;
Line 8,371 ⟶ 9,669:
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 8,382 ⟶ 9,680:
fact := n * factorial(pred(n));
end if;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Line 8,388 ⟶ 9,686:
=={{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 8,419 ⟶ 9,717:
acc when n <= 0
else
factorialHelper(acc * n, n-1);</
=={{header|SETL}}==
<
proc fact(n);
if (n < 2) then
Line 8,438 ⟶ 9,736:
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 8,481 ⟶ 9,779:
outint(f, 2); outint(factorial(f), 8); outimage
end
end</
{{out}}
<pre>factorials:
Line 8,492 ⟶ 9,790:
=={{header|Sisal}}==
Solution using a fold:
<
function main(x : integer returns integer)
Line 8,501 ⟶ 9,799:
end for
end function</
Simple example using a recursive function:
<
function main(x : integer returns integer)
Line 8,513 ⟶ 9,811:
end if
end function</
=={{header|Slate}}==
This is already implemented in the core language as:
<
"The standard recursive definition."
[
Line 8,524 ⟶ 9,822:
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}}==
Line 8,539 ⟶ 9,861:
===Iterative with fold===
{{works with|GNU Smalltalk}} {{works with|Smalltalk}}
<
my_factorial [
(self < 2)
Line 8,550 ⟶ 9,872:
7 factorial printNl.
7 my_factorial printNl.</
===Recursive===
<
factorial [
self < 0 ifTrue: [ self error: 'factorial is defined for natural numbers' ].
Line 8,559 ⟶ 9,881:
^self * ((self - 1) factorial)
]
].</
===Recursive (functional)===
Defining a ''local function'' (aka closure) named 'fac':
<
fac := [:n |
Line 8,572 ⟶ 9,894:
].
fac value:1000.</
{{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.
Line 8,591 ⟶ 9,913:
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 8,622 ⟶ 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,628 ⟶ 10,003:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
Line 8,650 ⟶ 10,025:
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 8,683 ⟶ 10,058:
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 8,697 ⟶ 10,072:
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 8,716 ⟶ 10,091:
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
Line 8,749 ⟶ 10,157:
goif
endif
</syntaxhighlight>
=={{header|Tailspin}}==
===Iterative===
<
templates factorial
when <0..> do
Line 8,760 ⟶ 10,168:
$@ !
end factorial
</syntaxhighlight>
===Recursive===
<
templates factorial
when <=0> do 1 !
when <0..> $ * ($ - 1 -> factorial) !
end factorial
</syntaxhighlight>
=={{header|Tcl}}==
Line 8,774 ⟶ 10,182:
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 8,805 ⟶ 10,213:
}
return $sum
}</
===Performance Analysis===
<
puts [rfact 30]
puts [ifact_caching 30]
Line 8,817 ⟶ 10,225:
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 8,830 ⟶ 10,238:
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 8,863 ⟶ 10,291:
%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 8,918 ⟶ 10,323:
formatnum=CENTER(num,+2," ")
PRINT "factorial of ",formatnum," = ",f
ENDLOOP</
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 8,943 ⟶ 10,348:
Via nPk function:
<
3628800</
===Functional===
<
3628800</
=={{header|UNIX Shell}}==
=== Iterative ===
{{works with|Bourne Shell}}
<
set -- "$1" 1
until test "$1" -lt 2; do
Line 8,960 ⟶ 10,365:
done
echo "$2"
}</
If <code>expr</code> uses 32-bit signed integers, then this function overflows after <code>factorial 12</code>.
Line 8,968 ⟶ 10,373:
{{works with|ksh93}}
{{works with|zsh}}
<
typeset n=$1 f=1 i
for ((i=2; i < n; i++)); do
Line 8,974 ⟶ 10,379:
done
echo $f
}</
* bash and zsh use 64-bit signed integers, overflows after <code>factorial 20</code>.
Line 8,981 ⟶ 10,386:
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 8,987 ⟶ 10,392:
else echo $(($1 * $(factorial $(($1-1)) ) ))
fi
}</
Or in [[Korn Shell|Korn style]]:
Line 8,994 ⟶ 10,399:
{{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 9,013 ⟶ 10,418:
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 9,027 ⟶ 10,435:
return result
end
</syntaxhighlight>
===Recursive===
<
decl int z
set z 1
Line 9,036 ⟶ 10,444:
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 9,225 ⟶ 10,542:
iterative 37! = 13763753091226345046315979581580902400000000
recursive 47! = 258623241511168180642964355153611979969197632389120000000000
iterative 47! = 258623241511168180642964355153611979969197632389120000000000</
=={{header|Verilog}}==
===Recursive===
<
function automatic [7:0] factorial;
Line 9,250 ⟶ 10,567:
$display("Factorial of 5 = %d", factorial(5));
end
endmodule</
=={{header|VHDL}}==
<
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
Line 9,327 ⟶ 10,644:
Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;
END Behavior ;</
=={{header|Vim Script}}==
<
if a:n < 2
return 1
Line 9,336 ⟶ 10,653:
return a:n * Factorial(a:n-1)
endif
endfunction</
=={{header|
Updated to V (Vlang) version 0.2.2
===Imperative===
<
fn factorial_i() {
Line 9,483 ⟶ 10,673:
fn main() {
factorial_i()
}</
===Recursive===
<
fn factorial_r(n int) int {
Line 9,499 ⟶ 10,689:
println('factorial($i) is: ${factorial_r(i)}')
}
}</
===Tail Recursive===
<
fn factorial_tail(n int) int {
Line 9,520 ⟶ 10,710:
println('factorial($i) is: ${factorial_tail(i)}')
}
}</
===Memoized===
<
struct Cache {
Line 9,546 ⟶ 10,736:
println('The $n-th Factorial is: $fac_n')
}
}</
{{out}}
<pre>The 0-th Factorial is: 1
Line 9,563 ⟶ 10,753:
===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 9,588 ⟶ 10,778:
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
Line 9,622 ⟶ 10,812:
end)
(export "fac" (func $fac)))
</syntaxhighlight>
<syntaxhighlight lang="webassembly">
(module
;; recursive, more compact version
Line 9,639 ⟶ 10,829:
)
)
</syntaxhighlight>
<syntaxhighlight lang="webassembly">
(module
;; recursive, refactored to use s-expressions
Line 9,656 ⟶ 10,846:
)
)
</syntaxhighlight>
<syntaxhighlight lang="webassembly">
(module
;; recursive, refactored to use s-expressions and named variables
Line 9,673 ⟶ 10,863:
)
)
</syntaxhighlight>
<syntaxhighlight lang="webassembly">
(module
;; iterative, generated by C compiler (LLVM) from recursive code!
Line 9,705 ⟶ 10,895:
)
)
</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 9,737 ⟶ 10,927:
[[!fac 10 !facM 10]]
}</
=={{header|Wrapl}}==
===Product===
<
===Recursive===
<
===Folding===
<
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<
import "./big" for BigInt
class Factorial {
Line 9,769 ⟶ 10,959:
var n = BigInt.new(24)
Fmt.print("Factorial(%(n)) iterative -> $,s", Factorial.iterative(n))
Fmt.print("Factorial(%(n)) recursive -> $,s", Factorial.recursive(n))</
{{out}}
Line 9,780 ⟶ 10,970:
{{works with|nasm}}
===Iterative===
<
section .text
Line 9,790 ⟶ 10,980:
mul ecx
loop .factor
ret</
===Recursive===
<
section .text
Line 9,811 ⟶ 11,001:
; base case: return 1
mov eax, 1
ret</
===Tail Recursive===
<
section .text
Line 9,829 ⟶ 11,019:
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 9,854 ⟶ 11,044:
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
else if (n < 0)
null
Line 9,891 ⟶ 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,898 ⟶ 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>
{{Out}}
<pre>
Line 9,917 ⟶ 11,100:
=={{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 9,931 ⟶ 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.
|