Python通过对非常大的整数求平方来实现幂函数的幂()

时间:2013-05-07 14:15:49

标签: python long-integer modulus exponentiation

我正在尝试推动我自己的pow(),它通过平方http://en.wikipedia.org/wiki/Exponentiation_by_squaring使用指数逐位迭代。如果这有助于您思考这个问题,那么这方面有一些问题:

Difference between the built-in pow() and math.pow() for floats, in Python?

Behavior of Python ** and % operators with big numbers

self made pow() c++

我正在自学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
>>> 

不确定这一切在哪里出现了悲惨的错误。

1 个答案:

答案 0 :(得分:2)

问题在于,当你这样做时,你正在乘以中间结果 x *= (x**2)...。相反,您只需要将新计算的值分配给x。只需将x*=替换为x=,如下所示:

def power(g_base,a,p_mod):
  x=1
  bits = "{0:b}".format(a)
  for i, bit in enumerate(bits):
    if bit=='1': x = (((x**2)*g_base)%p_mod)
    elif bit=='0': x = ((x**2)%p_mod)
  return x%p_mod

作为旁注,我不建议将多个语句放在由分号(;)分隔的一行中。虽然是合法的语法,但它并不是非常Pythonic。