我正在尝试实现RSA算法。我一直在研究扩展欧几里得算法,并尝试在不同的网站上实现代码。但是,对于我的某些解密操作,它没有给我正确的结果,因此我一直在调试,并注意到算法的不同实现会产生不同的结果。第一个实现来自Brilliant.org,第二个实现来自https://www.rookieslab.com/posts/extended-euclid-algorithm-to-find-gcd-bezouts-coefficients-python-cpp-code。
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def extended_euclid_gcd(a, b):
"""
Returns a list `result` of size 3 where:
Referring to the equation ax + by = gcd(a, b)
result[0] is gcd(a, b)
result[1] is x
result[2] is y
"""
s = 0; old_s = 1
t = 1; old_t = 0
r = b; old_r = a
while r != 0:
quotient = old_r/r
old_r, r = r, old_r - quotient*r
old_s, s = s, old_s - quotient*s
old_t, t = t, old_t - quotient*t
return old_r, old_s, old_t
对于a = 3,b = 25456,(源自稍微不太简单的示例https://www.di-mgt.com.au/rsa_alg.html),我分别得到了这两种实现的结果:
gcd: 1 x: -8485 y: 1
gcd: 25456 x: 0 y: 1
为什么它们不同?为什么第二个实现的gcd根本不是1?一个后续问题是,因为我试图按照链接中的示例进行操作,所以我的x值为负数。他们的答案是16971。我在这里阅读到https://math.stackexchange.com/questions/1001199/uniqueness-of-extended-euclidean-algorithm,扩展欧几里得算法找到最接近原点的答案。有没有办法指定最接近原点且为正数的答案?
old_r/r
中的“/”更改为“//”,它可能会起作用。 - President James K. Polk