多精度2-10进制下大整数模指数运算的实现
一、重复平方乘算法原理:
二、代码:(注:需调用上篇博客中Calculate的代码)
import Calculate
import time
def help_( x:str, n:int):
if n == 0:
return '1'
elif n==1:
return x
Mul = Calculate.BigMul(x, x, '10')
if n % 2 == 0:
return help_(Mul, int(n /2))
return Calculate.BigMul(help_(Mul, int((n - 1) / 2)), x, '10')
def Modular_operation(p:str,q:str,m:str):
q=int(q)
Mul=help_( p, q)
_,_,r=Calculate.BigDivision(Mul,m,'10')
return r
def pow1(p:str,q:str,m:str):
q=int(q)
Mul='1'
for i in range(q):
Mul=Calculate.BigMul(Mul,p,'10')
if (Calculate.Number_Comparision(Mul,m)>=0 ):
_,_,Mul=Calculate.BigDivision(Mul, m, '10')
_,_, r = Calculate.BigDivision(Mul, m, '10')
return r
def Repeated_square_multiplication_algorithm(p:str,q:str,m:str):
k_list = []
b = '1'
if q=='0':
return b
P = p
while (q!='0'):
_,q,k=Calculate.BigDivision(q, '2', '10')
k_list.append(k)
if k_list[0]=='1':
_,_,b=Calculate.BigDivision(q, m, '10')
for i in range(1,len(k_list)):
sqrt = Calculate.BigMul(P,P,"10")
_,_,P=Calculate.BigDivision(sqrt, m, '10')
if k_list[i]=='1':
P_MUL_b=Calculate.BigMul(P,b,'10')
_,_,b=Calculate.BigDivision(P_MUL_b,m,'10')
return b
p=input("请输入指数的底:")
q=input("请输入指数的方幂:")
m=input("请输入除数:")
start_time=time.time()
r=Modular_operation(p,q,m)
end_time=time.time()
dtime=end_time-start_time
print(r)
print("(分值递归求幂运算再求余)程序运行时间:%.8s s" % dtime)
start_time1=time.time()
r1=pow1(p,q,m)
end_time1=time.time()
dtime1=end_time1-start_time1
print(r1)
print("(边求幂运算之积边求余)程序运行时间:%.8s s" % dtime1)
start_time3=time.time()
r3=Repeated_square_multiplication_algorithm(p,q,m)
end_time3=time.time()
dtime3=end_time3-start_time3
print(r3)
print("(重复平方乘算法)程序运行时间:%.8s s" % dtime3)
start_time2=time.time()
p=int(p)
q=int(q)
m=int(m)
mul=pow(p,q)
r2=mul%m
end_time2=time.time()
dtime2=end_time2-start_time2
print(r2)
print("(调用大数据库求余)程序运行时间:%.8s s" % dtime2)
三、运行结果截图:
示例一:253596 mod 654
示例二:2596 mod 1234