66 lines
1.2 KiB
Python
66 lines
1.2 KiB
Python
import random, copy
|
|
|
|
|
|
#reszta kwadratowa
|
|
def resztaKwadratowa(a, p):
|
|
return potegowanieimod(a, int((p + 1) / 4), p)
|
|
|
|
|
|
#generuj liczbe pierwsza
|
|
def genPierwsza(bity):
|
|
while True:
|
|
a = random.getrandbits(bity)
|
|
if (fermat(100, a)):
|
|
return a
|
|
|
|
|
|
#sprawdza czy liczby są pierwsze
|
|
def fermat(dokladnosc, liczba):
|
|
i = 0
|
|
while i < dokladnosc:
|
|
a = random.randint(1, liczba - 1)
|
|
if pow(a, (liczba - 1), liczba) == 1:
|
|
i = i + 1
|
|
else:
|
|
return False
|
|
return True
|
|
|
|
|
|
#x * u + N * v = d
|
|
#Jeśli d == 1 to liczby są względnie pierwsze
|
|
#d to NWD
|
|
def euklides(x, N):
|
|
A,B,U,V = N, x, 0, 1
|
|
while True:
|
|
q = A // B
|
|
A_new = copy.deepcopy(B)
|
|
B = A - B * q
|
|
A = A_new
|
|
U_new = copy.deepcopy(V)
|
|
V = U - V * q
|
|
U = U_new
|
|
if B == 0:
|
|
break
|
|
d, u = A, U
|
|
v = (d - x * u)/N
|
|
return u, v, d
|
|
|
|
|
|
#liczba odwrotna do b w modulo n
|
|
def odwrotnosc(b, n):
|
|
u, _, d = euklides(b, n)
|
|
if d == 1:
|
|
return u % n
|
|
else:
|
|
return False
|
|
|
|
|
|
#potegowanie x do k w mod n
|
|
def potegowanieimod(x, k, n):
|
|
y = 1
|
|
while k > 0:
|
|
if k & 1:
|
|
y = y*x % n
|
|
x = x**2 % n
|
|
k = k >> 1
|
|
return y |