Factorial: Difference between revisions

5,959 bytes added ,  17 days ago
(37 intermediate revisions by 23 users not shown)
Line 362:
endif.
endform.</syntaxhighlight>
 
=={{header|Acornsoft Lisp}}==
 
===Recursive===
<syntaxhighlight lang="lisp">(defun factorial (n)
(cond ((zerop n) 1)
(t (times n (factorial (sub1 n))))))
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="lisp">(defun factorial (n (result . 1))
(loop
(until (zerop n) result)
(setq result (times n result))
(setq n (sub1 n))))
</syntaxhighlight>
 
=={{header|Action!}}==
Line 734 ⟶ 750:
<syntaxhighlight lang="apl"> FACTORIAL 6
720</syntaxhighlight>
{{works with|Dyalog APL}}
A recursive definition is also possible:
<syntaxhighlight lang="apl">
fac←{⍵>1 : ⍵×fac ⍵-1 ⋄ 1}
fac 5
120
</syntaxhighlight>
 
=={{header|AppleScript}}==
Line 1,149 ⟶ 1,172:
end // end of [factorial]
</syntaxhighlight>
 
=={{header|Asymptote}}==
===Iterative===
<syntaxhighlight lang="Asymptote">real factorial(int n) {
real f = 1;
for (int i = 2; i <= n; ++i)
f = f * i;
return f;
}
 
write("The factorials for the first 5 positive integers are:");
for (int j = 1; j <= 5; ++j)
write(string(j) + "! = " + string(factorial(j)));</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 1,299 ⟶ 1,335:
}
</syntaxhighlight>
 
===Imperative===
<syntaxhighlight lang="bash">factorial()
{
declare -nI _result=$1
declare -i n=$2
 
_result=1
while (( n > 0 )); do
let _result*=n
let n-=1
done
}
</syntaxhighlight>
 
(the imperative version will write to a variable, and can be used as <code>factorial f 10; echo $f</code>)
 
=={{header|BASIC}}==
Line 1,493 ⟶ 1,545:
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">'factorialaccurate examplebetween 1-12
'accurate between 1-12
 
print "version 1 without function"
let f = 1
 
for i = 1 to 12
alert "factorial"
input "enter an integer: ", n
 
let n = i
do
let f = 1
 
do
let f = f * n
let n = n - 1
 
let f = f * n
loop n > 0
let n = n - 1
 
loop n > 0
print f
 
print f, " ",
end</syntaxhighlight>
wait
 
next i
 
print newline, newline, "version 2 with function"
 
for i = 1 to 12
 
print factorial(i), " ",
 
next i</syntaxhighlight>
{{out| Output}}<pre>version 1 without function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600
 
version 2 with function
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 </pre>
 
==={{header|FreeBASIC}}===
Line 1,573 ⟶ 1,640:
end</syntaxhighlight>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1, @"Factorial", ( 0, 0, 300, 550 )
 
local fn factorialIterative( n as long ) as double
double f
long i
 
if ( n > 1 )
f = 1
for i = 2 to n
f = f * i
next
else
f = 1
end if
end fn = f
 
local fn factorialRecursive( n as long ) as double
double f
 
if ( n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
 
long i
 
for i = 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next
 
HandleEvents</syntaxhighlight>
 
Output:
<pre>
Iterative: 0 = 1
Recursive: 0 = 1
 
Iterative: 1 = 1
Recursive: 1 = 1
 
Iterative: 2 = 2
Recursive: 2 = 2
 
Iterative: 3 = 6
Recursive: 3 = 6
 
Iterative: 4 = 24
Recursive: 4 = 24
 
Iterative: 5 = 120
Recursive: 5 = 120
 
Iterative: 6 = 720
Recursive: 6 = 720
 
Iterative: 7 = 5040
Recursive: 7 = 5040
 
Iterative: 8 = 40320
Recursive: 8 = 40320
 
Iterative: 9 = 362880
Recursive: 9 = 362880
 
Iterative: 10 = 3628800
Recursive: 10 = 3628800
 
Iterative: 11 = 39916800
Recursive: 11 = 39916800
 
Iterative: 12 = 479001600
Recursive: 12 = 479001600
</pre>
 
==={{header|Gambas}}===
Line 1,996 ⟶ 1,985:
80 PRINT F
90 END</syntaxhighlight>
 
==={{header|Tiny Craft Basic}}===
<syntaxhighlight lang="basic">10 let f = 1
 
20 print "factorial"
30 input "enter an integer (1-34): ", n
 
40 rem loop
 
60 let f = f * n
70 let n = n - 1
 
80 if n > 0 then 40
 
90 print f
100 shell "pause"</syntaxhighlight>
 
==={{header|True BASIC}}===
Line 2,392 ⟶ 2,365:
^-1:_$>\:|
@.$<</syntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
Factorial on Church numerals in the lambda calculus is <code>λn.λf.n(λf.λn.n(f(λf.λx.n f(f x))))(λx.f)(λx.x)</code> (see https://github.com/tromp/AIT/blob/master/numerals/fac.lam) which in BLC is the 57 bits
<pre>000001010111000000110011100000010111101100111010001100010</pre>
 
=={{header|BQN}}==
Line 2,473 ⟶ 2,450:
true? x == 0 1 { x * factorial(x - 1)}
}</syntaxhighlight>
 
=={{header|Bruijn}}==
 
Implementation for numbers encoded in balanced ternary using Mixfix syntax defined in the Math module:
 
<syntaxhighlight lang="bruijn">
:import std/Math .
 
factorial [∏ (+1) → 0 | [0]]
 
:test ((factorial (+10)) =? (+3628800)) ([[1]])
</syntaxhighlight>
 
=={{header|Burlesque}}==
Line 3,809 ⟶ 3,798:
 
<syntaxhighlight lang="text">
procfunc factorial n . r .
r = 1
for i = 2 to n
r *= i
.
return r
.
callprint factorial 7 r
print r
</syntaxhighlight>
 
Line 4,100 ⟶ 4,089:
=={{header|Elm}}==
 
==={{header|Recursive}}===
 
<syntaxhighlight lang="elm">
Line 4,108 ⟶ 4,097:
</syntaxhighlight>
 
==={{header|Tail Recursive}}===
 
<syntaxhighlight lang="elm">
Line 4,120 ⟶ 4,109:
</syntaxhighlight>
 
==={{header|Functional}}===
 
<syntaxhighlight lang="elm">
Line 4,732 ⟶ 4,721:
in out
</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"Factorial", ( 0, 0, 300, 550 )
 
local fn factorialIterative( n as long ) as double
double f
long i
 
if ( n > 1 )
f = 1
for i = 2 to n
f = f * i
next
else
f = 1
end if
end fn = f
 
local fn factorialRecursive( n as long ) as double
double f
 
if ( n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
 
long i
 
for i = 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Iterative: 0 = 1
Recursive: 0 = 1
 
Iterative: 1 = 1
Recursive: 1 = 1
 
Iterative: 2 = 2
Recursive: 2 = 2
 
Iterative: 3 = 6
Recursive: 3 = 6
 
Iterative: 4 = 24
Recursive: 4 = 24
 
Iterative: 5 = 120
Recursive: 5 = 120
 
Iterative: 6 = 720
Recursive: 6 = 720
 
Iterative: 7 = 5040
Recursive: 7 = 5040
 
Iterative: 8 = 40320
Recursive: 8 = 40320
 
Iterative: 9 = 362880
Recursive: 9 = 362880
 
Iterative: 10 = 3628800
Recursive: 10 = 3628800
 
Iterative: 11 = 39916800
Recursive: 11 = 39916800
 
Iterative: 12 = 479001600
Recursive: 12 = 479001600
</pre>
 
 
=={{header|GAP}}==
Line 5,233 ⟶ 5,303:
return n * factorial(n - 1);
];</syntaxhighlight>
 
=={{header|Insitux}}==
 
{{trans|Clojure}}
 
'''Iterative'''
 
<syntaxhighlight lang="insitux">
(function factorial n
(... *1 (range 2 (inc n))))
</syntaxhighlight>
 
'''Recursive'''
 
<syntaxhighlight lang="insitux">
(function factorial x
(if (< x 2)
1
(*1 x (factorial (dec x)))))
</syntaxhighlight>
 
=={{header|Io}}==
Line 5,951 ⟶ 6,041:
=={{header|langur}}==
=== Folding ===
<syntaxhighlight lang="langur">val .factorial = ffn(.n) fold(ffn{*}, .x x2 .y, pseries. .n)
writeln .factorial(7)</syntaxhighlight>
 
{{works with|langur|0.6.13}}
<syntaxhighlight lang="langur">val .factorial = f fold(f{x}, 2 .. .n)
writeln .factorial(7)</syntaxhighlight>
 
=== Recursive ===
<syntaxhighlight lang="langur">val .factorial = ffn(.x) { if(.x < 2: 1; .x x* self(.x - 1)) }
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative ===
<syntaxhighlight lang="langur">val .factorial = ffn(.i) {
var .answer = 1
for .x in 2 .. .i {
.answer x*= .x
}
.answer
}
 
writeln .factorial(7)</syntaxhighlight>
 
=== Iterative Folding ===
<syntaxhighlight lang="langur">val .factorial = fn(.n) { for[=1] .x in .n { _for *= .x } }
{{works with|langur|0.7.0}}
<syntaxhighlight lang="langur">val .factorial = f(.n) for[=1] .x in .n { _for x= .x }
writeln .factorial(7)</syntaxhighlight>
 
Line 6,019 ⟶ 6,105:
acc.
}.</syntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
n is number
 
procedure:
sub factorial
parameters:
n is number
result is number
local data:
i is number
m is number
procedure:
store 1 in result
in m solve n + 1
for i from 1 to m step 1 do
multiply result by i in result
repeat
end sub
create statement "get factorial of $ in $" executing factorial
 
get factorial of 5 in n
display n lf
</syntaxhighlight>
{{out}}
<pre>
120
</pre>
 
=={{header|Lean}}==
Line 6,204 ⟶ 6,319:
// iterative
function factorialit n
put 1 into f
if n > 1 then
repeat with i = 1 to n
Line 7,162 ⟶ 7,277:
4 factorial . ( => 24 )
10 factorial . ( => 3628800 )</syntaxhighlight>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
def 'math factorial' [] {[$in 1] | math max | 1..$in | math product}
 
..10 | each {math factorial}
</syntaxhighlight>
{{out}}
<pre>
╭────┬─────────╮
│ 0 │ 1 │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 6 │
│ 4 │ 24 │
│ 5 │ 120 │
│ 6 │ 720 │
│ 7 │ 5040 │
│ 8 │ 40320 │
│ 9 │ 362880 │
│ 10 │ 3628800 │
╰────┴─────────╯
</pre>
 
=={{header|Nyquist}}==
Line 7,177 ⟶ 7,315:
(* n (factorial (1- n)))))</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<syntaxhighlight lang="oberon2modula2">
MODULE Factorial;
IMPORT
Line 7,244 ⟶ 7,382:
Recursive 8! =40320
Recursive 9! =362880
</pre>
 
=={{header|Oberon-07}}==
Almost identical to the Oberon-2 sample, with minor output formatting differences.<br/>
Oberon-2 allows single or double quotes to delimit strings whereas Oberon-07 only allows double quotes. Also, the LONGINT type does not exist in Oberon-07 (though some compilers may accept is as a synonym for INTEGER).
<syntaxhighlight lang="modula2">
MODULE Factorial;
IMPORT
Out;
 
VAR
i: INTEGER;
 
PROCEDURE Iterative(n: INTEGER): INTEGER;
VAR
i, r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
FOR i := n TO 2 BY -1 DO
r := r * i
END;
RETURN r
END Iterative;
 
PROCEDURE Recursive(n: INTEGER): INTEGER;
VAR
r: INTEGER;
BEGIN
ASSERT(n >= 0);
r := 1;
IF n > 1 THEN
r := n * Recursive(n - 1)
END;
RETURN r
END Recursive;
 
BEGIN
FOR i := 0 TO 9 DO
Out.String("Iterative ");Out.Int(i,0);Out.String("! =");Out.Int(Iterative(i),8);Out.Ln;
END;
Out.Ln;
FOR i := 0 TO 9 DO
Out.String("Recursive ");Out.Int(i,0);Out.String("! =");Out.Int(Recursive(i),8);Out.Ln;
END
END Factorial.
</syntaxhighlight>
{{out}}
<pre>
Iterative 0! = 1
Iterative 1! = 1
Iterative 2! = 2
Iterative 3! = 6
Iterative 4! = 24
Iterative 5! = 120
Iterative 6! = 720
Iterative 7! = 5040
Iterative 8! = 40320
Iterative 9! = 362880
 
Recursive 0! = 1
Recursive 1! = 1
Recursive 2! = 2
Recursive 3! = 6
Recursive 4! = 24
Recursive 5! = 120
Recursive 6! = 720
Recursive 7! = 5040
Recursive 8! = 40320
Recursive 9! = 362880
</pre>
 
Line 8,707 ⟶ 8,915:
Memoized:
<syntaxhighlight lang="red">fac: function [n][m: #(0 1) any [m/:n m/:n: n * fac n - 1]]</syntaxhighlight>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Facts 0 10>;
}
 
Facts {
s.N s.Max, <Compare s.N s.Max>: '+' = ;
s.N s.Max = <Prout <Symb s.N>'! = ' <Fact s.N>>
<Facts <+ s.N 1> s.Max>;
};
 
Fact {
0 = 1;
s.N = <* s.N <Fact <- s.N 1>>>;
};</syntaxhighlight>
{{out}}
<pre>0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800</pre>
 
=={{header|Relation}}==
Line 9,154 ⟶ 9,390:
===Imperative===
An imperative style using a mutable variable:
<syntaxhighlight lang="scala">def factorial(n: Int)={
def factorial(n: Int) = {
var res = 1
for (i <- 1 to n)
res *= i
res
}
}</syntaxhighlight>
</syntaxhighlight>
 
===Recursive===
Using naive recursion:
<syntaxhighlight lang="scala">def factorial(n: Int): Int =
def if factorial(n: == 0Int): 1Int =
if (n < 1) 1
else n * factorial(n-1)</syntaxhighlight>
else n * factorial(n - 1)
</syntaxhighlight>
 
Using tail recursion with a helper function:
<syntaxhighlight lang="scala">def factorial(n: Int) = {
def factorial(n: Int) = {
@tailrec def fact(x: Int, acc: Int): Int = {
if (x < 2) acc else fact(x - 1, acc * x)
}
fact(n, 1)
}
}</syntaxhighlight>
</syntaxhighlight>
 
===Stdlib .product===
Line 9,183 ⟶ 9,425:
===Folding===
Using folding:
<syntaxhighlight lang="scala">def factorial(n: Int) =
def factorial(n: Int) =
(2 to n).foldLeft(1)(_ * _)</syntaxhighlight>
(2 to n).foldLeft(1)(_ * _)
</syntaxhighlight>
 
===Using implicit functions to extend the Int type===
Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:
<syntaxhighlight lang="scala">implicit def IntToFac(i : Int) = new {
implicit def IntToFac(i : Int) = new {
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}
}</syntaxhighlight>
</syntaxhighlight>
 
{{out | Example used in the REPL}}
Line 9,203 ⟶ 9,449:
=={{header|Scheme}}==
===Recursive===
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))</syntaxhighlight>
</syntaxhighlight>
The following is tail-recursive, so it is effectively iterative:
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))</syntaxhighlight>
</syntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="scheme">(define (factorial n)
(define (factorial n)
(do ((i 1 (+ i 1))
(accum 1 (* accum i)))
((> i n) accum)))</syntaxhighlight>
</syntaxhighlight>
 
===Folding===
<syntaxhighlight lang="scheme">;Using a generator and a function that apply generated values to a function taking two arguments
;Using a generator and a function that apply generated values to a function taking two arguments
 
;A generator knows commands 'next? and 'next
Line 9,242 ⟶ 9,497:
 
(factorial 8)
;40320</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Scilab}}==
Line 9,564 ⟶ 9,820:
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}}==
Line 10,054 ⟶ 10,331:
{{out}}
<pre><1,1,2,6,24,120,720,5040,40320></pre>
 
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">@factorial ( n* -: fact* )
ORAk ?{ POP2 #0001 JMP2r }
DUP2 #0001 SUB2 factorial MUL2
JMP2r</syntaxhighlight>
 
=={{header|Verbexx}}==
Line 10,530 ⟶ 10,813:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
import "./big" for BigInt
 
class Factorial {
Line 10,635 ⟶ 10,918:
int N; \range: 0..12
return if N<2 then 1 else N*FactRecur(N-1);</syntaxhighlight>
 
=={{header|YAMLScript}}==
<syntaxhighlight lang="yaml">
#!/usr/bin/env ys-0
 
defn main(n):
say: "$n! = $factorial(n)"
 
defn factorial(x):
apply *: 2 .. x
</syntaxhighlight>
 
=={{header|Zig}}==
{{Works with|Zig|0.11.0}}
Supports all integer data types, and checks for both overflow and negative numbers; returns null when there is a domain error.
<syntaxhighlight lang="zig">
const stdout = @import("std").io.getStdOut().outStream();
 
pub fn factorial(comptime Num: type, n: i8) ?Num {
return if (@typeInfo(Num) != .Int)
@compileError("factorial called with numnon-integral type: " ++ @typeName(Num))
else if (n < 0)
null
Line 10,650 ⟶ 10,943:
var fac: Num = 1;
while (i <= n) : (i += 1) {
ifconst tmp = (@mulWithOverflow(Num, fac, i, &fac));
if (tmp[1] != break :calc null;0)
break :calc null; // overflow
fac = tmp[0];
} else break :calc fac;
};
Line 10,657 ⟶ 10,952:
 
pub fn main() !void {
tryconst stdout.print("-1! = {}\n@import(", std").{factorialio.getStdOut(i32, -1)}.writer();
 
try stdout.print("0! = {}\n", .{factorial(i32, 0)});
try stdout.print("5-1! = {?}\n", .{factorial(i32, 5-1)});
try stdout.print("330!(64 bit) = {?}\n", .{factorial(i64i32, 330)}); // not vailid i64 factorial
try stdout.print("335! = {?}\n", .{factorial(i128i32, 335)}); // biggest facorial possible
try stdout.print("3433!(64 bit) = {?}\n", .{factorial(i128i64, 3433)}); // willnot overflowvalid i64 factorial
try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible
try stdout.print("34! = {?}\n", .{factorial(i128, 34)}); // will overflow
}
</syntaxhighlight>
885

edits