Category talk:Wren-math: Difference between revisions
Content added Content deleted
(→Source code: Added two more convenience methods to Nums class.) |
(→Source code: Added multinomial and binomial methods to Int class. Restricted factorial method to n < 19.) |
||
Line 164: | Line 164: | ||
} |
} |
||
// Returns the factorial of 'n' |
// Returns the factorial of 'n'. |
||
static factorial(n) { |
static factorial(n) { |
||
if (!(n is Num && n >= 0 |
if (!(n is Num && n >= 0 && n < 19)) { |
||
Fiber.abort("Argument must be a non-negative integer < 19.") |
|||
} |
|||
if (n < 2) return 1 |
if (n < 2) return 1 |
||
var fact = 1 |
var fact = 1 |
||
Line 172: | Line 174: | ||
return fact |
return fact |
||
} |
} |
||
// Returns the multinomial coefficient of n over a list f where sum(f) == n. |
|||
static multinomial(n, f) { |
|||
if (!(n is Num && n >= 0 && n < 19)) { |
|||
Fiber.abort("First argument must be a non-negative integer < 19.") |
|||
} |
|||
if (!(f is List)) Fiber.abort("Second argument must be a list.") |
|||
var sum = f.reduce { |acc, i| acc + i } |
|||
if (n != sum) { |
|||
Fiber.abort("The elements of the list must sum to 'n'.") |
|||
} |
|||
var prod = 1 |
|||
for (e in f) { |
|||
if (e < 0) Fiber.abort("The elements of the list must be non-negative integers.") |
|||
if (e > 1) prod = prod * factorial(e) |
|||
} |
|||
return factorial(n)/prod |
|||
} |
|||
// Returns the binomial coefficent of n over k. |
|||
static binomial(n, k) { multinomial(n, [k, n-k]) } |
|||
// Determines whether 'n' is prime using a wheel with basis [2, 3]. |
// Determines whether 'n' is prime using a wheel with basis [2, 3]. |