AcWing 3124. BSGS
原题链接
中等
作者:
皓首不倦
,
2021-05-01 15:00:41
,
所有人可见
,
阅读 376
import math
def bsgs(a, b, p):
if b % p == 1:
return 0
k = int(math.sqrt(p)) + 1
mm = {} # 保存(a ^ beta) % p -> beta 的映射关系
val = b
for beta in range(k):
mm[val] = beta
val *= a
val %= p
ak = 1 # ak 表示 (a ^ (alpha * k)) % p 的数值
for i in range(k):
ak *= a
ak %= p
val = 1
for alpha in range(1, k+1):
val *= ak
val %= p
if val in mm:
beta = mm[val]
return alpha * k - beta
return None
while True:
a, p, b = map(int, input().split())
if a == 0 and p == 0 and b == 0:
break
ret = bsgs(a, b, p)
if ret is None:
print("No Solution")
else:
print(ret)