2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,5 +1,13 @@
The '''Factorial Function''' of a positive integer, ''n'', is defined as the product of the sequence ''n'', ''n''-1, ''n''-2, ...1 and the factorial of zero, 0, is [[wp:Factorial#Definition|defined]] as being 1.
;Definitions:
:* &nbsp; The &nbsp; '''Factorial Function''' &nbsp; of a positive integer, &nbsp; <big> ''n'', </big> &nbsp; is defined as the product of the sequence:
<big><big> ''n'', &nbsp; ''n''-1, &nbsp; ''n''-2, &nbsp; ... &nbsp; 1 </big></big>
:* &nbsp; The factorial of &nbsp; '''0''' &nbsp; (zero) &nbsp; is [[wp:Factorial#Definition|defined]] as being &nbsp; 1 &nbsp; (unity).
;Task:
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Support for trapping negative &nbsp; <big> ''n'' </big> &nbsp; errors is optional.
<br><br>

View file

@ -0,0 +1,2 @@
!6
720

View file

@ -0,0 +1 @@
FACTORIAL{×/}

View file

@ -0,0 +1,2 @@
FACTORIAL 6
720

View file

@ -1,8 +1,8 @@
on factorial(x)
if x < 0 then return 0
set R to 1
repeat while x > 1
set {R, x} to {R * x, x - 1}
end repeat
return R
if x < 0 then return 0
set R to 1
repeat while x > 1
set {R, x} to {R * x, x - 1}
end repeat
return R
end factorial

View file

@ -1,5 +1,10 @@
-- factorial :: Int -> Int
on factorial(x)
if x < 0 then return 0
if x > 1 then return x * (my factorial(x - 1))
return 1
if x > 1 then
x * (factorial(x - 1))
else if x = 1 then
1
else
0
end if
end factorial

View file

@ -0,0 +1,63 @@
-- factorial :: Int -> Int
on factorial(x)
script product
on lambda(a, b)
a * b
end lambda
end script
foldl(product, 1, range(1, x))
end factorial
-- TEST
on run
factorial(11)
--> 39916800
end run
-- GENERIC LIBRARY PRIMITIVES
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to lambda(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- range :: Int -> Int -> [Int]
on range(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end range
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : f
end script
end if
end mReturn

View file

@ -1,2 +1,2 @@
def rFact
rFact = { (it > 1) ? it * rFact(it - 1) : 1 }
rFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger }

View file

@ -1 +1 @@
(0..6).each { println "${it}: ${rFact(it)}" }
def iFact = { (it > 1) ? (2..it).inject(1 as BigInteger) { i, j -> i*j } : 1 }

View file

@ -1 +1,17 @@
def iFact = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 }
def time = { Closure c ->
def start = System.currentTimeMillis()
def result = c()
def elapsedMS = (System.currentTimeMillis() - start)/1000
printf '(%6.4fs elapsed)', elapsedMS
result
}
def dashes = '---------------------'
print " n! elapsed time "; (0..15).each { def length = Math.max(it - 3, 3); printf " %${length}d", it }; println()
print "--------- -----------------"; (0..15).each { def length = Math.max(it - 3, 3); print " ${dashes[0..<length]}" }; println()
[recursive:rFact, iterative:iFact].each { name, fact ->
printf "%9s ", name
def factList = time { (0..15).collect {fact(it)} }
factList.each { printf ' %3d', it }
println()
}

View file

@ -1 +1,27 @@
var factorial = n => (n < 2) ? 1 : n * factorial(n - 1);
(function () {
'use strict';
// factorial :: Int -> Int
function factorial(x) {
return range(1, x)
.reduce(function (a, b) {
return a * b;
}, 1);
}
// range :: Int -> Int -> [Int]
function range(m, n) {
var a = Array(n - m + 1),
i = n + 1;
while (i-- > m) a[i - m] = i;
return a;
}
return factorial(18);
})();

View file

@ -0,0 +1 @@
6402373705728000

View file

@ -0,0 +1 @@
var factorial = n => (n < 2) ? 1 : n * factorial(n - 1);

View file

@ -0,0 +1,20 @@
(function (n) {
'use strict';
// factorial :: Int -> Int
let factorial = (n) => range(1, n).reduce(product, 1);
// product :: Num -> Num -> Num
let product = (a, b) => a * b,
// range :: Int -> Int -> [Int]
range = (m, n) =>
Array.from({
length: (n - m) + 1
}, (_, i) => m + i)
return factorial(n);
})(18);

View file

@ -0,0 +1,20 @@
fun facti(n: Int) = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
var ans = 1L
for (i in 2..n) ans *= i
ans
}
}
fun factr(n: Int): Long = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
n < 2 -> 1L
else -> n * factr(n - 1)
}
fun main(args: Array<String>) {
val n = 20
println("$n! = " + facti(n))
println("$n! = " + factr(n))
}

View file

@ -0,0 +1,16 @@
HAI 1.3
HOW IZ I Faktorial YR Number
BOTH SAEM 1 AN BIGGR OF Number AN 1
O RLY?
YA RLY
FOUND YR 1
NO WAI
FOUND YR PRODUKT OF Number AN I IZ Faktorial YR DIFFRENCE OF Number AN 1 MKAY
OIC
IF U SAY SO
IM IN YR Loop UPPIN YR Index WILE DIFFRINT Index AN 13
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR Loop
KTHXBYE

View file

@ -0,0 +1,7 @@
fact = setmetatable({[0] = 1}, {
__call = function(t,n)
if n < 0 then return 0 end
if not t[n] then t[n] = n * t(n-1) end
return t[n]
end
})

View file

@ -0,0 +1,48 @@
##################################
# Factorial; iterative #
# By Keith Stellyes :) #
# Targets Mars implementation #
# August 24, 2016 #
##################################
# This example reads an integer from user, stores in register a1
# Then, it uses a0 as a multiplier and target, it is set to 1
# Pseudocode:
# a0 = 1
# a1 = read_int_from_user()
# while(a1 > 1)
# {
# a0 = a0*a1
# DECREMENT a1
# }
# print(a0)
.text ### PROGRAM BEGIN ###
### GET INTEGER FROM USER ###
li $v0, 5 #set syscall arg to READ_INTEGER
syscall #make the syscall
move $a1, $v0 #int from READ_INTEGER is returned in $v0, but we need $v0
#this will be used as a counter
### SET $a1 TO INITAL VALUE OF 1 AS MULTIPLIER ###
li $a0,1
### Multiply our multiplier, $a1 by our counter, $a0 then store in $a1 ###
loop: ble $a1,1,exit # If the counter is greater than 1, go back to start
mul $a0,$a0,$a1 #a1 = a1*a0
subi $a1,$a1,1 # Decrement counter
j loop # Go back to start
exit:
### PRINT RESULT ###
li $v0,1 #set syscall arg to PRINT_INTEGER
#NOTE: syscall 1 (PRINT_INTEGER) takes a0 as its argument. Conveniently, that
# is our result.
syscall #make the syscall
#exit
li $v0, 10 #set syscall arg to EXIT
syscall #make the syscall

View file

@ -0,0 +1,13 @@
var factorial = function(number) {
var i = 1;
var result = 1;
while(i <= number) {
result *= i;
i += 1;
}
return result;
};
$print(factorial(10));

View file

@ -1,2 +1,2 @@
sub postfix:<!> ( UInt:D $n ) is looser(&prefix:<->) { [*] 2..$n }
sub postfix:<!> (Int $n) { [*] 2..$n }
say 5!;

View file

@ -3,6 +3,6 @@ fact(N, NF) :-
fact(X, X, F, F) :- !.
fact(X, N, FX, F) :-
FX1 is FX * X,
X1 is X + 1,
FX1 is FX * X1,
fact(X1, N, FX1, F).

View file

@ -1,27 +1,5 @@
from cmath import *
# Coefficients used by the GNU Scientific Library
g = 7
p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
def gamma(z):
z = complex(z)
# Reflection formula
if z.real < 0.5:
return pi / (sin(pi*z)*gamma(1-z))
else:
z -= 1
x = p[0]
for i in range(1, g+2):
x += p[i]/(z+i)
t = z + g + 0.5
return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x
def factorial(n):
return gamma(n+1)
print "factorial(-0.5)**2=",factorial(-0.5)**2
for i in range(10):
print "factorial(%d)=%s"%(i,factorial(i))
z=1
if n>1:
z=n*factorial(n-1)
return z

View file

@ -1,5 +1,27 @@
from cmath import *
# Coefficients used by the GNU Scientific Library
g = 7
p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
def gamma(z):
z = complex(z)
# Reflection formula
if z.real < 0.5:
return pi / (sin(pi*z)*gamma(1-z))
else:
z -= 1
x = p[0]
for i in range(1, g+2):
x += p[i]/(z+i)
t = z + g + 0.5
return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x
def factorial(n):
z=1
if n>1:
z=n*factorial(n-1)
return z
return gamma(n+1)
print "factorial(-0.5)**2=",factorial(-0.5)**2
for i in range(10):
print "factorial(%d)=%s"%(i,factorial(i))

View file

@ -1,21 +1,18 @@
/*REXX program computes the factorial of a non-negative integer. */
numeric digits 100000 /*100k digs: handles N up to 25k.*/
parse arg n /*get argument from command line. */
if n='' then call er 'no argument specified'
if arg()>1 | words(n)>1 then call er 'too many arguments specified.'
if \datatype(n,'N') then call er "argument isn't numeric: " n
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 /*define factorial product so far.*/
/*REXX program computes the factorial of a non-negative integer. */
numeric digits 100000 /*100k digits: handles N up to 25k.*/
parse arg n /*obtain optional argument from the CL.*/
if n='' then call er 'no argument specified.'
if arg()>1 | words(n)>1 then call er 'too many arguments specified.'
if \datatype(n,'N') then call er "argument isn't numeric: " n
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 /*define the factorial product (so far)*/
do j=2 to n; !=!*j /*compute the factorial the hard way. */
end /*j*/ /* [↑] where da rubber meets da road. */
/*══════════════════════════════════════where da rubber meets da road──┐*/
do j=2 to n; !=!*j /*compute the ! the hard way◄───┘*/
end /*j*/
/*══════════════════════════════════════════════════════════════════════*/
say n'! is ['length(!) "digits]:" /*display # of digits in factorial*/
say /*add some whitespace to output. */
say !/1 /*normalize the factorial product.*/
exit /*stick a fork in it, we're done. */
/*─────────────────────────────────ER subroutine────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; say; exit 13
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say ! /*display the factorial product. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error***'; say; say arg(1); say; exit 13

View file

@ -1,53 +1,22 @@
/*REXX program computes the factorial of a non-negative integer, and */
/* automatically adjusts the number of digits to accommodate the answer.*/
/* ┌────────────────────────────────────────────────────────────────┐
Some factorial lengths
10 ! = 7 digits
20 ! = 19 digits
52 ! = 68 digits
104 ! = 167 digits
208 ! = 394 digits
416 ! = 394 digits (8 deck shoe)
1k ! = 2,568 digits
10k ! = 35,660 digits
100k ! = 456,574 digits
1m ! = 5,565,709 digits
10m ! = 65,657,060 digits
100m ! = 756,570,556 digits
Only one result is shown below for pratical reasons.
This version of the REXX interpreter is essentially limited
to around 8 million digits, but with some programming
tricks, it could yield a result up to 16 million digits.
Also, the Regina REXX interpreter is limited to an exponent
9 digits, i.e.: 9.999...999e+999999999
*/
numeric digits 99 /*99 digs initially, then expanded*/
numeric form /*exponentiated #s =scientric form*/
parse arg n /*get argument from command line. */
if n='' then call er 'no argument specified'
if arg()>1 | words(n)>1 then call er 'too many arguments specified.'
if \datatype(n,'N') then call er "argument isn't numeric: " n
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 /*define factorial product so far.*/
/*REXX program computes the factorial of a non-negative integer, and it automatically */
/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/
numeric digits 99 /*99 digits initially, then expanded. */
parse arg n /*obtain optional argument from the CL.*/
if n='' then call er 'no argument specified'
if arg()>1 | words(n)>1 then call er 'too many arguments specified.'
if \datatype(n,'N') then call er "argument isn't numeric: " n
if \datatype(n,'W') then call er "argument isn't a whole number: " n
if n<0 then call er "argument can't be negative: " n
!=1 /*define the factorial product (so far)*/
do j=2 to n; !=!*j /*compute the factorial the hard way. */
if pos(.,!)==0 then iterate /*is the ! in exponential notation? */
parse var ! 'E' digs /*extract exponent of the factorial, */
numeric digits digs+digs%10 /* ··· and increase it by ten percent.*/
end /*j*/ /* [↑] where da rubber meets da road. */
/*══════════════════════════════════════where da rubber meets da road──┐*/
do j=2 to n; !=!*j /*compute the ! the hard way◄───┘*/
if pos('E',!)==0 then iterate /*is ! in exponential notation? */
parse var ! 'E' digs /*pick off the factorial exponent.*/
numeric digits digs+digs%10 /* and incease it by ten percent.*/
end /*j*/
/*══════════════════════════════════════════════════════════════════════*/
say n'! is ['length(!) "digits]:" /*display # of digits in factorial*/
say /*add some whitespace to output. */
say !/1 /*normalize the factorial product.*/
exit /*stick a fork in it, we're done. */
/*─────────────────────────────────ER subroutine────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; say; exit 13
say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/
say /*add some whitespace to the output. */
say !/1 /*normalize the factorial product. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
er: say; say '***error!***'; say; say arg(1); say; exit 13

View file

@ -1,27 +1,28 @@
/*REXX program computes the factorial of a number, striping trailing 0's*/
numeric digits 200 /*start with two hundred digits. */
parse arg N .; if N=='' then N=0 /*get argument from command line.*/
!=1 /*define factorial produce so far*/
/*═══════════════════════════════════════where the rubber meets the road*/
do j=2 to N /*compute factorial the hard way.*/
old!=! /*save old ! in case of overflow.*/
!=!*j /*multiple old factorial with J.*/
if pos('E',!)\==0 then do /*is ! in exponential notation?*/
d=digits() /*D temporarly stores # digits.*/
numeric digits d+d%10 /*add 10% do digits.*/
!=old!*j /*recalculate for the lost digits*/
end /*IFF ≡ if and only if. [↓] */
if right(!,1)==0 then !=strip(!,,0) /*strip trailing zeroes IFF the*/
end /*j*/ /* [↑] right-most digit is zero.*/
z=0 /*the number of trailing zeroes. */
do v=5 by 0 while v<=N /*calculate # of trailing zeroes.*/
z=z+N%v /*bump Z if multiple power of 5. */
v=v*5 /*calculate the next power of 5. */
end /*while v≤N*/ /* [↑] advance V by ourselves.*/
/*══════════════════════════════════════════════════════════════════════*/
!=! || copies(0,z) /*add water to rehydrate the !. */
if z==0 then z='no' /*use gooder English for message.*/
say N'! is ['length(!) " digits with " z ' trailing zeroes]:'
say /*display blank line (whitespace)*/
say ! /* ··· and display the ! product.*/
/*stick a fork in it, we're done.*/
/*REXX program computes the factorial of an integer, striping trailing zeroes. */
numeric digits 200 /*start with two hundred digits. */
parse arg N .; if N=='' then N=0 /*obtain the optional argument from CL.*/
!=1 /*define the factorial product so far. */
do j=2 to N /*compute factorial the hard way. */
old!=! /*save old product in case of overflow.*/
!=!*j /*multiple the old factorial with J. */
if pos(.,!) \==0 then do /*is the ! in exponential notation?*/
d=digits() /*D temporarily stores number digits.*/
numeric digits d+d%10 /*add 10% to the decimal digits. */
!=old! * j /*re─calculate for the "lost" digits.*/
end /*IFF ≡ if and only if. [↓] */
parse var ! '' -1 _ /*obtain the right-most digit of ! */
if _==0 then !=strip(!,,0) /*strip trailing zeroes IFF the ... */
end /*j*/ /* [↑] ... right-most digit is zero. */
z=0 /*the number of trailing zeroes in ! */
do v=5 by 0 while v<=N /*calculate number of trailing zeroes. */
z=z + N%v /*bump Z if multiple power of five.*/
v=v*5 /*calculate the next power of five. */
end /*v*/ /* [↑] we only advance V by ourself.*/
!=! || copies(0, z) /*add water to rehydrate the product. */
if z==0 then z='no' /*use gooder English for the message. */
say N'! is ['length(!) " digits with " z ' trailing zeroes]:'
say /*display blank line (for whitespace).*/
say ! /*display the factorial product. */
/*stick a fork in it, we're all done. */

View file

@ -16,8 +16,7 @@ end
# Iterative with Range#inject
def factorial_inject(n)
return 1 if n.zero?
(1..n).inject { |prod, i| prod * i }
(1..n).inject(1){ |prod, i| prod * i }
end
# Iterative with Range#reduce, requires Ruby 1.8.7

View file

@ -1,10 +1,10 @@
const func bigInteger: factorial (in bigInteger: n) is func
result
var bigInteger: result is 1_;
var bigInteger: fact is 1_;
local
var bigInteger: i is 0_;
begin
for i range 1_ to n do
result *:= i;
fact *:= i;
end for;
end func;

View file

@ -1,8 +1,8 @@
const func bigInteger: factorial (in bigInteger: n) is func
result
var bigInteger: result is 1_;
var bigInteger: fact is 1_;
begin
if n > 1_ then
result := n * factorial(pred(n));
fact := n * factorial(pred(n));
end if;
end func;

View file

@ -0,0 +1,14 @@
begin
integer procedure factorial( n );
integer n;
begin
integer fact, i;
fact := 1;
if n > 1 then
for i := 2 step 1 until n do
fact := fact * i;
factorial := fact
end;
outint( factorial( 6 ), 5);
outimage
end

View file

@ -0,0 +1,7 @@
function! Factorial(n)
if a:n < 2
return 1
else
return a:n * Factorial(a:n-1)
endif
endfunction