(base, exponent, modulus)
| 48 | * @param {number} modulus |
| 49 | */ |
| 50 | const modularExponentiation = (base, exponent, modulus) => { |
| 51 | if (modulus === 1) return 0 // after all, any x % 1 = 0 |
| 52 | |
| 53 | let result = 1 |
| 54 | base %= modulus // make sure that base < modulus |
| 55 | |
| 56 | while (exponent > 0) { |
| 57 | // if exponent is odd, multiply the result by the base |
| 58 | if (exponent % 2 === 1) { |
| 59 | result = (result * base) % modulus |
| 60 | exponent-- |
| 61 | } else { |
| 62 | exponent = exponent / 2 // exponent is even for sure |
| 63 | base = (base * base) % modulus |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | return result |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Test if a given number n is prime or not. |
no outgoing calls
no test coverage detected