An algorithm for finding the square root of a module (I will add more scores after the answer is complete)

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

#! /usr/bin/python

# code =gbk

Import mathematics

Def quick _ algorithm (a, b, c): # y = a b% c, and the b power of a is divided by C.

a = a % c

ans = 1

# We don't need to think about B.

And b! = 0: # Fermat Theorem

If b & kloc-0/:

ans = (ans * a) % c

b & gt& gt= 1

a = (a * a) % c

Return the answer

Def IsHaveMoSqrt(x, P):# Whether there is a modular square root y*y=x mod p, given x, p, judge whether there is y..

ret = quick_algorithm(x,(P- 1)//2,P)

If ret== 1:

Return True

Otherwise:

Returns False

Def GetMoSqrt(x, P):# Find the square root of module y*y=x mod p, where x is known and p finds y.

if(IsHaveMoSqrt(x,P)== 1):

t=0

S = p-1# p-1= (2t) * s//s is an odd number.

And s%2==0:

s=s//2

t=t+ 1

if(t== 1):

ret = quick_algorithm(x,(s+ 1)//2,P)

Return (ret, P-ret)

elif(t & gt; =2):

X _ = fast algorithm (x, P-2, p)

n= 1

while(IsHaveMoSqrt(n,P)== 1):

n=n+ 1

B = fast algorithm (n, s, p)

Print (b)

ret = quick_algorithm(x,(s+ 1)//2,P)#t- 1

t_=0

while(t- 1 & gt; 0):

if(quick_algorithm(x_*ret*ret,2**(t-2),P)== 1):

Ret = return

Otherwise:

ret = ret *(b * *(2 * * t _)% P

t=t- 1

t_=t_+ 1

Return (ret, P-ret)

Otherwise:

Return (-2, -2)

Otherwise:

Returns (-1,-1)

Defsecp256k1getybyx (x): # y 2 = x 3+7 (mod p) Find y according to x.

a =(x * x * x+7)% 0x fffffffffffffffffffffffffffffffffffffffffffffff 2f

ret = GetMoSqrt(a,0x fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 2f)

Return to ret

if __name__ == "__main__ ":

If true:

X = 0x79be667E9DCBBa55A 06295ce870b07029bfcdb2dce28d959f28 1 5b1798 # The private key is1,and the corresponding public key is X.

Ret = secp256k1getybyx (x) # secp256k1,and find y according to x.

print("x=%x" % (x))

print("y=%x" % (ret[0]))

print("y=%x" % (ret[ 1]))

Print ("")

X= 1#x minimum value

Ret = secp256k1getybyx (x) # secp256k1,and find y according to x.

print("x=%x" % (x))

print("y=%x" % (ret[0]))

print("y=%x" % (ret[ 1]))

Print ("")

X = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF C2F-3 # x Maximum value.

Ret = secp256k1getybyx (x) # secp256k1,and find y according to x.

print("x=%x" % (x))

print("y=%x" % (ret[0]))

print("y=%x" % (ret[ 1]))

Print ("")

Enter ()

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※