简体   繁体   English

平方总是求幂法

[英]square always exponentiation method

besides the square-and-multiply method, there is this method square-and-multiply-always, and i am trying to implement it in python. 除了平方乘方法外,还有总是平方乘的方法,我正在尝试在python中实现它。 My problem is that during searching i found a pseudocode for it, here and i implemented it in python but it does not yield the correct results in comparison to pow function. 我的问题是,搜索过程中我发现了一个伪吧, 在这里我实现了它在python,但它不能在比较战俘功能产生正确的结果。
The pseudo code can be found in the link above or in this screenshot . 伪代码可以在上面的链接中或此屏幕快照中找到

My implementation is 我的实现是

def square_and_multiply_always(base, exp, mod):
    R0=1
    R1 = base
    c = '{0:b}'.format(exp)
    i=len(c)
    t=0
    while i>=0:
        if(t==0):
            Rt=R0
        elif(t==1):
            Rt=R1
        else:
             print("t != 0 or 1")
        R0=(R0*Rt)%mod
        a=int(c[i-1])
        t=(t^a)
        i=i-1+t
    return R0

i managed to find my mistakes so here is a proper code for future searches that end up here 我设法找到了我的错误,所以这里有一个适合将来最终搜索的正确代码

def square_and_multiply_always(base, exp, mod):
    R0=1
    R1 = base
    c = '{0:b}'.format(exp)
    i=len(c)-1
    t=0
    c=c[::-1]
    while(i>=0):
        if(t==0):
            Rt=R0
        elif(t==1):
            Rt=R1
        else:
            print("t != 0 or 1")
        R0=(R0*Rt)%mod
        d=int(c[i])
        t=(t^d)
        i=i-1+t
    return R0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM