我在 Python 3.x 上尝试蒙哥马利乘法算法。该算法伪代码如下:
Input: Modulus N(n bit), gcd(n, 2) = 1, Multipler: A (n bit), Multiplicant: B (n bit)
Output: R = (A x B x 2 ^ (-n)) mod N
R = 0
for (i = 0; i < n; i++)
{
q = (R + A(i) * B) mod 2
R = (R + A(i) * B + q * N) / 2
}
print(R)
编写的 Python 3.x 代码如下:
#!/usr/bin/python3
N = 41
A = 13
B = 17
n = N.bit_length()
R = 0
for i in range(0, n):
q = int(R + (A & (1 << i) != 0) * B) % 2
R = int((R + (A & (1 << i) != 0) * B + q * N) / 2)
print("Result:", R % N)
但是,代码没有给出正确的结果。问题是什么?
谢谢回答。