Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Ref: https://stackoverflow.com/q/29569927
- const modInverse = (num, mod) => {
- let a = BigInt(num)
- let m = BigInt(mod)
- let q = [BigInt(0), BigInt(1)]
- for (let i = 2; m % a > 0; i++) {
- const quotient = m / a
- const remainder = m % a
- q[i] = q[i - 2] - (q[i - 1] * quotient)
- m = a
- a = remainder
- }
- let inverse = q[q.length - 1]
- if (inverse < 0) {
- inverse += BigInt(mod)
- }
- return inverse
- }
Add Comment
Please, Sign In to add comment