deflim(a,m): # 限定a在[-m/2, m/2]范围内 if a>m//2: a -= m elif a<-(m//2): a+=m return a
defprime_solver(p): if p == 2: # 对p==2的情况进行特判 return1,1 a = 2 f = 0 whilenot f: # 二次剩余求解 m = (p-1)//2 ifpow(a,m,p)>1: f = 1 x=pow(a,(m//2),p) else: a = int(gmpy2.next_prime(a)) a = x b = 1 while1: # 求a,b m1 = (a**2+b**2)//p if m1 == 1: break u = a % m1 v = b % m1 v = lim(v,m1) u = lim(u,m1) a1 = (u*a+v*b)//m1 b1 = (u*b-v*a)//m1 a = a1 b = b1 assert a*a+b*b == p returnabs(a),abs(b)
defjudge(n):# 最终分解出的p,q的约束条件 return gmpy2.is_prime(n) or gmpy2.is_prime(n)
defsearch(p,q,cnt): # 深搜求解 if cnt == len(factors): if judge(p) and judge(q): print(p,q) return search(p*roots[cnt][0]+q*roots[cnt][1],abs(p*roots[cnt][1]-q*roots[cnt][0]),cnt+1) search(p*roots[cnt][1]+q*roots[cnt][0],abs(p*roots[cnt][0]-q*roots[cnt][1]),cnt+1)
factors = [] roots = []
for f in factors: if f%4 == 1or f == 2: roots.append(prime_solver(f)) else: raise Exception("4k+3!") print(roots) search(roots[0][0],roots[0][1],1) search(roots[0][1],roots[0][0],1)
deflim(a,m): # 限定a在[-m/2, m/2]范围内 if a>m//2: a -= m elif a<-(m//2): a+=m return a
defprime_solver(p): if p == 2: return1,1 a = 2 f = 0 whilenot f: # 二次剩余求解 m = (p-1)//2 ifpow(a,m,p)>1: f = 1 x=pow(a,(m//2),p) else: a = int(gmpy2.next_prime(a)) a = x b = 1 while1: # 求a,b m1 = (a**2+b**2)//p if m1 == 1: break u = a % m1 v = b % m1 v = lim(v,m1) u = lim(u,m1) a1 = (u*a+v*b)//m1 b1 = (u*b-v*a)//m1 a = a1 b = b1 assert a*a+b*b == p returnabs(a),abs(b)
defjudge(n):# 最终分解出的p,q的约束条件 return gmpy2.is_prime(n) or gmpy2.is_prime(n)
defsearch(p,q,cnt): # 深搜求解 if cnt == len(factors): if judge(p) and judge(q): print(p,q) return search(p*roots[cnt][0]+q*roots[cnt][1],abs(p*roots[cnt][1]-q*roots[cnt][0]),cnt+1) search(p*roots[cnt][1]+q*roots[cnt][0],abs(p*roots[cnt][0]-q*roots[cnt][1]),cnt+1) # factordb.com factors = [2,5,2341,191429240956028917,18808725088317359977,1021179744308298062426500817712456533] roots = []
for f in factors: if f%4 == 1or f == 2: roots.append(prime_solver(f)) else: raise Exception("4k+3!") print(roots) search(roots[0][0],roots[0][1],1) search(roots[0][1],roots[0][0],1)