Issues (4)

index.js (1 issue)

1
/**
2
 *
3
 * @author Henrik Fredriksson
4
 * @param {*} n Integer to be tested for primality
5
 * @param {number} [k=100] iteratons
0 ignored issues
show
The parameter k does not exist. Did you maybe forget to remove this comment?
Loading history...
6
 * @returns {boolean} True if n is prime otherwise false
7
 */
8
function isPrime(n, k = 100) {
9
  if (n === 2 || n === 3) { return true }
10
11
  const smallPrimes = [2, 3, 5, 7, 11, 13, 17]
12
13
  const res = smallPrimes.map(x => n % x === 0).filter(x => x).includes(true)
14
  if (res) return false
15
16
  if (
17
    n % 2 === 0 || n % 3 === 0 || n % 5 === 0 || n % 7 === 0 || n < 2) {
18
    return false
19
  }
20
21
  // Write (n - 1) as 2^s * d
22
  let s = 0
23
  let d = n - 1
24
  while (d % 2 === 0) {
25
    d /= 2
26
    ++s
27
  }
28
29
  const witness = n => {
30
    return Math.floor(Math.random() * (n - 2)) + 2
31
  }
32
33
  while (k--) {
34
    let a = Math.pow(witness(n), s)
35
36
    if (a % n === 1) continue
37
38
    let testFails = false
39
    for (let i = 0; i < s; i++) {
40
      a = Math.pow(a, 2) % n
41
      if (a === n - 1) {
42
        testFails = true
43
        break
44
      }
45
    }
46
47
    if (testFails) return false
48
  }
49
  return true
50
}
51
52
module.exports = isPrime
53