modular arithmetic course - challenge 7 - symbole de legendre et racine carrée mod p
This commit is contained in:
parent
a3db668081
commit
e79ee10479
2 changed files with 72 additions and 0 deletions
|
|
@ -41,3 +41,57 @@ def quadratic_residue(N: int, x: int):
|
|||
if pow(i, 2, N) == x:
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
# Challenge 7 - Legendre's symbol
|
||||
def _is_quadratic_residue(x: int, N: int) -> bool:
|
||||
if pow(x, (N - 1) // 2, N) == 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _tonelli_shanks(x, p):
|
||||
q = p - 1
|
||||
k = 0
|
||||
while q % 2 == 0:
|
||||
q = q // 2
|
||||
k += 1
|
||||
if q % 2 == 0:
|
||||
raise ValueError
|
||||
z = 1
|
||||
while _is_quadratic_residue(z, p):
|
||||
z += 1
|
||||
c, t, r = pow(z, q, p), pow(x, q, p), pow(x, (q + 1) // 2, p)
|
||||
while True:
|
||||
if t == 0:
|
||||
return 0
|
||||
if t == 1:
|
||||
return r
|
||||
i = 1
|
||||
while i < k:
|
||||
if pow(t, 1 << i, p) == 1:
|
||||
break
|
||||
i += 1
|
||||
b = pow(c, 1 << (k - i - 1), p)
|
||||
k = i
|
||||
c = pow(b, 2, p)
|
||||
t = t * pow(b, 2) % p
|
||||
r = r * b % p
|
||||
|
||||
|
||||
def legendre_symbol(N: int, candidates: [int]):
|
||||
"""Find the square root of x mod N using Legendre's symbol.
|
||||
Args:
|
||||
N: a prime integer.
|
||||
x: a list of integer that may be quadratic residues.
|
||||
Returns:
|
||||
The square root of the first element in x which is a quadratic residue.
|
||||
"""
|
||||
for x in candidates:
|
||||
if _is_quadratic_residue(x, N):
|
||||
# TODO find the square root of x mod N
|
||||
try:
|
||||
return _tonelli_shanks(x, N)
|
||||
except:
|
||||
return None
|
||||
return None
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue