Modular Exponentiation的功能,我的两行代码有什么问题?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
答案
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
以上是关于Modular Exponentiation的功能,我的两行代码有什么问题?的主要内容,如果未能解决你的问题,请参考以下文章
[POJ] #1002# Exponentiation : 大数乘法