当我使用这些参数(pow(1,3,3))时,为什么会收到此错误消息?:
sage: pow(1,3,3)
3
3/2
3/2
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/home/kai/<ipython console> in <module>()
/home/kai/<ipython console> in pow(a, e, n)
/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/rings/rational.so in sage.rings.rational.Rational.__mod__ (sage/rings/rational.c:19891)()
/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/rings/integer.so in sage.rings.integer.Integer.inverse_mod (sage/rings/integer.c:32726)()
ZeroDivisionError: Inverse does not exist.
POW():
def pow(a,e,n):
....: num = 1
....: while e >= 1:
....: print(e)
....: if (e%2) == 1:
....: num = (num*a) % n
....: e = e/2
....: print(e)
....: a = (a*a) % n
....: return num
....:
答案 0 :(得分:3)
通过实现的平方算法进行的模幂运算应该使用整数。
e = e/2
返回Rational 3/2
。
您应该将其转换为整数e = (e/2).floor()
。
答案 1 :(得分:-1)
a = (a*a) % n
a = 1 * 1%1 a - &gt; 0 这意味着在你的情况下是0,所以这里
num = (num*a) % n
您将获得0%3。
编辑: 在python中可以做3/2%3吗?