MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / modularExponentiation

Function modularExponentiation

Maths/FermatPrimalityTest.js:50–68  ·  view source on GitHub ↗
(base, exponent, modulus)

Source from the content-addressed store, hash-verified

48 * @param {number} modulus
49 */
50const 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.

Callers 2

fermatPrimeCheckFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected