数据如下:
p=
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
g=
11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
h=
3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333
python代码如下:
1.基础版本
import gmpy2
import time
# 初始参数
p = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
g = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
h = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333
B = 2 ** 20 # 1048576
# 创建空字典
left_result = {}
# 优化前,令x=Bx0+x1
start = time.process_time()
s0 = gmpy2.f_mod(h, p)#定值,放在循环体外,减小计算次数,提高运算速度
for x1 in range(1048577):
s1 = gmpy2.powmod(g,x1,p)
s2 = gmpy2.invert(s1,p)
s3 = gmpy2.f_mod(s0*s2,p)
left_result[s3] = x1 # key-value
r = gmpy2.powmod(g, B, p)
for x0 in range(len(left_result)):
c = gmpy2.powmod(r, x0, p)
if c in left_result:
x = gmpy2.mul(B, x0) + left_result[c]
print("x0=", x0)
print("x1=", left_result[c])
print("x=", x)
break
end = time.process_time()
print("The running time totals is",end - start, "s")
2.优化
import gmpy2
import time
#初始参数
p = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
g = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
h = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333
B = 2 ** 20#1048576
#创建空字典
left_result = {}
#优化后,令x=Bx0-x1
start=time.process_time()
s0 = gmpy2.f_mod(h, p)#定值,只需计算一次,放在循环外
for x1 in range(1048577):
s1 = gmpy2.powmod(g,x1,p)
s2 = gmpy2.f_mod(s1*s0,p)
left_result[s2] = x1 #key-value
r = gmpy2.powmod(g,B,p)
for x0 in range(len(left_result)):
c = gmpy2.powmod(r,x0,p)
if c in left_result:
x = gmpy2.mul(B,x0) - left_result[c]
print("x0=",x0)
print("x1=", left_result[c])
print("x=", x)
break
end=time.process_time()
print("The running time totals is",end - start, "s")
可得结果如下:
1.基础
2.优化
注意:由于数据太大,必须简化处理,否则运行时间指数增长。程序中用到的函数解释:
文末给出gmpy2的参考文档(英文),有兴趣可以阅读:
链接:gmpy2使用英文版.pdf
提取码:1234