Modular Exponentiation的功能,我的两行代码有什么问题?

时间:2018-03-05 03:26:34

标签: python cryptography

我们被要求为这个函数添加两行代码,我们的教授给我们提供了Modular Exponentiation。我已经进行了多次测试并最终得到了错误的答案。我想知道我添加的两行代码是否有意义,所以这里是:

def powmod(a,b,m):
    bin=binary(b) #List containing the digits of b in binary
    length = len(bin) #Number of digits in when b is written in binary
    product=1  # Use this to store the current product of terms
    for i in range(0,length):
        if bin[i]==1:
            # Insert ONE line of code here.
              product = product * a %m <----- INSERTED CODE
        #Insert ONE line of code here to square a and reduce it modulo m.
              a = a **2%m <----- INSERTED CODE
    return product

输入:powmod(13,654321,2018)
输出我得到:1213
正确输出:1835

1 个答案:

答案 0 :(得分:0)

不是必需的结果1835?

def binary(b):
    digits=[]
    while b>0:
        if b%2==1:
            digits.append(1)
            b = b-1
        else:
            digits.append(0)
            b = b/2
    return digits
def powmod(a,b,m):
    bin=binary(b) #List containing the digits of b in binary
    length = len(bin) #Number of digits in when b is written in binary
    product=1  # Use this to store the current product of terms
    for i in range(0,length):
        if bin[i]==1:
            # Insert ONE line of code here.
              # product = product * a %
              pass #return a #does nothing if it enters this condition
        #Insert ONE line of code here to square a and reduce it modulo m.

        product = product * a % m
    return product

print powmod(13,654321,2018)

Output: 1835