import math
def gcd(a, b):
if a > b:
a, b, = b, a
while a:
a, b = b % a, a
return b
# 拓展欧几里得算法,求a, b最大公约数,同时求出裴蜀定理中的一组系数x, y, 满足x*a + y*b = gcd(a, b)
def exp_gcd(a, b):
flag = True
if a > b:
flag = False
a, b = b, a
if a == 0:
return (b, 0, 1) if flag else (b, 1, 0)
gcd_val, x, y = exp_gcd(b%a, a)
new_x = y - x * (b // a)
new_y = x
return (gcd_val, new_x, new_y) if flag else (gcd_val, new_y, new_x)
# 求val对mod取模的逆元, 也就是求出的ans满足(val * ans) 和 1 对 mod 求模同余
def get_mul_mod_rev_meta(val, mod):
gcd_val, x, _ = exp_gcd(val, mod)
# 这个地方x求出来可能是负数,如果需要将x变为正数,将x取对mode // gcd_val取一下模,python里面负数取模是正数, x + k * (mod // gcd_val)是x的通解
# x % (mod // gcd_val) 就是x最小正整数解
return None if gcd_val != 1 else x % (mod // gcd_val)
# 常规BSGS算法
def bsgs(a, b, p):
if b % p == 1 % p:
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
# 拓展BSGS算法
def exp_bsgs(a, b, p):
if b % p == 1 % p:
return 0
d = gcd(a, p)
if d == 1:
return bsgs(a, b, p)
if b % d != 0:
return None
rev_meta = get_mul_mod_rev_meta(a//d, p//d)
return exp_bsgs(a, b//d * rev_meta, p//d) + 1
while True:
a, p, b = map(int, input().split())
if a == 0 and p == 0 and b == 0:
break
ret = exp_bsgs(a, b, p)
if ret is None:
print("No Solution")
else:
print(ret)