tsanth

JS: Modular Inverse via the Extended Euclidean Algorithm

Sep 25th, 2019 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Ref: https://stackoverflow.com/q/29569927
  2. const modInverse = (num, mod) => {
  3.   let a = BigInt(num)
  4.   let m = BigInt(mod)
  5.  
  6.   let q = [BigInt(0), BigInt(1)]
  7.   for (let i = 2; m % a > 0; i++) {
  8.     const quotient = m / a
  9.     const remainder = m % a
  10.  
  11.     q[i] = q[i - 2] - (q[i - 1] * quotient)
  12.  
  13.     m = a
  14.     a = remainder
  15.   }
  16.  
  17.   let inverse = q[q.length - 1]
  18.   if (inverse < 0) {
  19.     inverse += BigInt(mod)
  20.   }
  21.  
  22.   return inverse
  23. }
Add Comment
Please, Sign In to add comment