UNPKG

1.36 kBJavaScriptView Raw
1'use strict'
2
3const deepMap = require('../../utils/collection/deepMap')
4
5function factory (type, config, load, typed) {
6 const gamma = load(require('./gamma'))
7 const latex = require('../../utils/latex')
8
9 /**
10 * Compute the factorial of a value
11 *
12 * Factorial only supports an integer value as argument.
13 * For matrices, the function is evaluated element wise.
14 *
15 * Syntax:
16 *
17 * math.factorial(n)
18 *
19 * Examples:
20 *
21 * math.factorial(5) // returns 120
22 * math.factorial(3) // returns 6
23 *
24 * See also:
25 *
26 * combinations, gamma, permutations
27 *
28 * @param {number | BigNumber | Array | Matrix} n An integer number
29 * @return {number | BigNumber | Array | Matrix} The factorial of `n`
30 */
31 const factorial = typed('factorial', {
32 'number': function (n) {
33 if (n < 0) {
34 throw new Error('Value must be non-negative')
35 }
36
37 return gamma(n + 1)
38 },
39
40 'BigNumber': function (n) {
41 if (n.isNegative()) {
42 throw new Error('Value must be non-negative')
43 }
44
45 return gamma(n.plus(1))
46 },
47
48 'Array | Matrix': function (n) {
49 return deepMap(n, factorial)
50 }
51 })
52
53 factorial.toTex = {
54 1: `\\left(\${args[0]}\\right)${latex.operators['factorial']}`
55 }
56
57 return factorial
58}
59
60exports.name = 'factorial'
61exports.factory = factory