我正在尝试通过平方http://en.wikipedia.org/wiki/Exponentiation_by_squaring来滚动我自己的 pow() ,它使用幂运算一点一点地遍历二进制。如果这有助于您思考这个问题,那么这方面有一些问题:
Python 中用于浮点数的内置 pow() 和 math.pow() 之间的区别?
我正在自学 Python,所以这可能是我犯的一些简单错误。
def power(g_base,a,p_mod):
x=1; b=[1]; bits = "{0:b}".format(a)
for bit in bits:
if bit=='1': x *= (((x**2)*g_base)%p_mod)
elif bit=='0': x *= ((x**2)%p_mod)
else: x *= 1
#t = [b.append(((x**2)*g_base)%p_mod) if bit == '1' else b.append((x**2)%p_mod) for bit in bits]
return x%p_mod
a,b,c=5,2,8
#a,b,c=31,21,12
print "power(): ",power(a,b,c)
print "pow(): ",pow(a,b,c)
输出正确的是 31,21,12,错误的是 5,2,8:
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
power(): 5
pow(): 1
>>> ================================ RESTART ================================
>>>
power(): 7
pow(): 7
>>>
不知道这一切都在哪里发生了可悲的错误。