我只是通过模乘逆的定义和我的理解:
ax = 1 (mod m)
=> m is a divisor of ax -1 and x is the inverse we are looking for
=> ax - 1 = q*m (where q is some integer)
And the most important thing is gcd(a, m) = 1
i.e. a and m are co-primes
在你的情况下:
ed = 1 mod((p-1)(q-1)) //p, q and e are given
=> ed - 1 = z*((p-1)(q-1)) //where z is some integer and we need to find d
再次从维基百科条目中,可以使用扩展的欧几里得 GCD 算法计算模逆,该算法执行以下操作:
ax + by = g //where g = gcd(a,b) i.e. a and b are co-primes
//The extended gcd algorithm gives us the value of x and y as well.
在您的情况下,方程式将是这样的:
ed - z*((p-1)(q-1)) = 1; //Compare it with the structure given above
a -> e
x -> d
b -> (p-1)(q-1)
y -> z
因此,如果我们只是将该算法应用于这种情况,我们将得到 和 的d
值z
。
对于ax + by = gcd(a,b)
,扩展的 gcd 算法可能看起来像(source):
function xgcd(a, b) {
if (b == 0) {
return [1, 0, a];
}
temp = xgcd(b, a % b);
x = temp[0];
y = temp[1];
d = temp[2];
return [y, x-y*Math.floor(a/b), d];
}
该算法运行时间为O(log(m)^2),假设 |a| < m,并且通常比取幂更有效。
我不知道 javascript 中是否有内置函数。我怀疑是否存在,而且我是算法的粉丝,所以我想你可能想尝试一下这种方法。您可以摆弄它并更改它以处理您的值范围,我希望它能让您朝着正确的方向开始。