python的平方运算符_Python通过对非常大的整数进行平方来实现pow()以求幂

1586010002-jmsa.png

I'm trying to roll my own pow() which goes over a binary bit by bit using exponentiation by squaring http://en.wikipedia.org/wiki/Exponentiation_by_squaring. There were some questions in this area if this helps you in thinking about this problem:

I'm teaching myself Python so it may be some simple mistake I'm making.

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)

The output is right with 31,21,12 and wrong with 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

>>>

Not sure where this all went tragically wrong.

解决方案

The problem is that you are multiplying the intermediate results when you do

x *= (x**2).... Instead, you just need to assign the newly computed value to x. Simply replace x*= with x= as follows:

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

As a side note, I would not recommend putting multiple statements in one line separated by a semicolon (;). Although legal syntax, it is not very Pythonic.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值