UNPKG

fast-mod-exp

Version:

Fast modular exponentiation function, for numbers and bigints.

24 lines (23 loc) 498 B
/* HELPERS */ const fme_bigint = (a, b, n) => { let r = 1n; let x = a % n; while (b) { if (b & 1n) { r = (r * x) % n; } x = (x * x) % n; b = b >> 1n; } return r; }; function fme(a, b, n) { if (typeof a === 'bigint' && typeof b === 'bigint' && typeof n === 'bigint') { return fme_bigint(a, b, n); } else { return Number(fme_bigint(BigInt(a), BigInt(b), BigInt(n))); } } /* EXPORT */ export default fme;