1 | 'use strict'
|
2 |
|
3 | const isInteger = require('../../utils/number').isInteger
|
4 |
|
5 | function factory (type, config, load, typed) {
|
6 | const factorial = load(require('./factorial'))
|
7 | const product = require('./product')
|
8 | |
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | const permutations = typed('permutations', {
|
34 | 'number | BigNumber': factorial,
|
35 | 'number, number': function (n, k) {
|
36 | if (!isInteger(n) || n < 0) {
|
37 | throw new TypeError('Positive integer value expected in function permutations')
|
38 | }
|
39 | if (!isInteger(k) || k < 0) {
|
40 | throw new TypeError('Positive integer value expected in function permutations')
|
41 | }
|
42 | if (k > n) {
|
43 | throw new TypeError('second argument k must be less than or equal to first argument n')
|
44 | }
|
45 |
|
46 | return product((n - k) + 1, n)
|
47 | },
|
48 |
|
49 | 'BigNumber, BigNumber': function (n, k) {
|
50 | let result, i
|
51 |
|
52 | if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
|
53 | throw new TypeError('Positive integer value expected in function permutations')
|
54 | }
|
55 | if (k.gt(n)) {
|
56 | throw new TypeError('second argument k must be less than or equal to first argument n')
|
57 | }
|
58 |
|
59 | result = new type.BigNumber(1)
|
60 | for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
|
61 | result = result.times(i)
|
62 | }
|
63 |
|
64 | return result
|
65 | }
|
66 |
|
67 |
|
68 | })
|
69 |
|
70 | permutations.toTex = undefined
|
71 |
|
72 | return permutations
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | function isPositiveInteger (n) {
|
81 | return n.isInteger() && n.gte(0)
|
82 | }
|
83 |
|
84 | exports.name = 'permutations'
|
85 | exports.factory = factory
|