UNPKG

2.03 kBJavaScriptView Raw
1'use strict'
2
3const deepMap = require('../../utils/collection/deepMap')
4
5function factory (type, config, load, typed) {
6 /**
7 * Test whether a value is prime: has no divisors other than itself and one.
8 * The function supports type `number`, `bignumber`.
9 *
10 * The function is evaluated element-wise in case of Array or Matrix input.
11 *
12 * Syntax:
13 *
14 * math.isPrime(x)
15 *
16 * Examples:
17 *
18 * math.isPrime(3) // returns true
19 * math.isPrime(-2) // returns false
20 * math.isPrime(0) // returns false
21 * math.isPrime(-0) // returns false
22 * math.isPrime(0.5) // returns false
23 * math.isPrime('2') // returns true
24 * math.isPrime([2, 17, 100]) // returns [true, true, false]
25 *
26 * See also:
27 *
28 * isNumeric, isZero, isNegative, isInteger
29 *
30 * @param {number | BigNumber | Array | Matrix} x Value to be tested
31 * @return {boolean} Returns true when `x` is larger than zero.
32 * Throws an error in case of an unknown data type.
33 */
34 const isPrime = typed('isPrime', {
35 'number': function (x) {
36 if (x < 2) {
37 return false
38 }
39 if (x === 2) {
40 return true
41 }
42 if (x % 2 === 0) {
43 return false
44 }
45 for (let i = 3; i * i <= x; i += 2) {
46 if (x % i === 0) {
47 return false
48 }
49 }
50 return true
51 },
52
53 'BigNumber': function (x) {
54 if (x.lt(2)) {
55 return false
56 }
57 if (x.equals(2)) {
58 return true
59 }
60 if (x.mod(2).isZero()) {
61 return false
62 }
63 for (let i = type.BigNumber(3); i.times(i).lte(x); i = i.plus(1)) {
64 if (x.mod(i).isZero()) {
65 return false
66 }
67 }
68 return true
69 },
70
71 'Array | Matrix': function (x) {
72 return deepMap(x, isPrime)
73 }
74 })
75
76 return isPrime
77}
78
79exports.name = 'isPrime'
80exports.factory = factory