详情关注公众号:算法面试题
//返回a的p次方对n取模的值
function superPow(a, p, n) {
let b = String(p).split("").map(item => Number(item));
function powMod(x, y) {
let res = 1;
for(let i = 0; i < y; i++) {
res = res * x % n;
}
return res;
}
let res = 1;
a %= n;
for(let i = b.length - 1; i >= 0; i--) {
res = powMod(a, b[i]) * res % n;
a = powMod(a, 10);
}
return res;
}
//以p=5,q=11,n=55,r=40,e=3,d=27为例
const e = 3,
d = 27,
n = 55;
//返回加密后的数组
function encrypt(arr) {
return arr.map(item => superPow(item, e, n));
}
//对加密的数组进行解密,返回解密后的数组
function decrypt(arr) {
return arr.map(item => superPow(item, d, n));
}
console.log(encrypt([3, 4, 5, 6, 7])); //[27, 9, 15, 51, 13]
console.log(decrypt([27, 9, 15, 51, 13])); //[3, 4, 5, 6, 7]