deflegendre(a,p): symbol = pow(a, (p - 1) // 2, p) if symbol == p - 1: return -1 return symbol
deftonelli(a,p): if a == 0or legendre(a,p) != 1: return0 q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: returnpow(n, (p + 1) // 4, p) z = 2 while legendre(z, p) != -1: z += 1 m = s c = pow(z, q, p) t = pow(a, q, p) r = pow(a, (q +1) // 2, p) while t!= 1: t2 = t i = 0 while t2 != 1and i < m: t2 = pow(t2, 2, p) i += 1 b = pow(c, 2 ** (m - i - 1), p) m = i c = (b * b) % p t = (t * c) % p r = (r * b) % p return r