def sqrt(x): p = x.rational_part s, t = p.numerator, p.denominator if p == 0: return Quadratic() elif p < 0: raise NotImplementedError elif x.quadratic_power == 0: if is_square(s) and is_square(t): return Quadratic(Fraction(isqrt(s), isqrt(t))) r = Fraction(1, t) p = s * t prime_power_list = [] for prime, x_power in zip(primes, x.quadratic_part or (0, ) * len(primes)): power = 0 while p % prime == 0: p //= prime power += 1 r *= prime**(power >> 1) prime_power_list.append(((power & 1) << x.quadratic_power) | x_power) if not is_square(p): return return Quadratic(r * isqrt(p), x.quadratic_power + 1, tuple(prime_power_list))
def quadratic_solve(a,b,c): disc = (b**2) - (4*a*c) if disc >0: a2 = (2*a) x0= (-b + gmpy2.isqrt(disc))//a2 x1= (-b - gmpy2.isqrt(disc))//a2 return x0,x1
def verify_A3(A, N): ''' serves factor_3 ''' c = -A**2 + A + 6*N b = mpz(1) a = mpz(1) if (b**2 - 4*a*c) < 0: return False x_candidates = ( gmpy2.div((-b + gmpy2.isqrt(b**2 - 4*a*c)), 2*a), gmpy2.div((-b - gmpy2.isqrt(b**2 - 4*a*c)), 2*a)) for x in x_candidates: if x < 0: continue # 2q < 3p p = gmpy2.div((A + x), 3) q = gmpy2.div((A - x - 1), 2) if p*q == N: return p, q # 3p < 2q p = gmpy2.div((A - x - 1), 3) q = gmpy2.div((A + x), 2) if p*q == N: return p, q return False
def verify_A3(A, N): ''' serves factor_3 ''' c = -A**2 + A + 6 * N b = mpz(1) a = mpz(1) if (b**2 - 4 * a * c) < 0: return False x_candidates = (gmpy2.div((-b + gmpy2.isqrt(b**2 - 4 * a * c)), 2 * a), gmpy2.div((-b - gmpy2.isqrt(b**2 - 4 * a * c)), 2 * a)) for x in x_candidates: if x < 0: continue # 2q < 3p p = gmpy2.div((A + x), 3) q = gmpy2.div((A - x - 1), 2) if p * q == N: return p, q # 3p < 2q p = gmpy2.div((A - x - 1), 3) q = gmpy2.div((A + x), 2) if p * q == N: return p, q return False
def fermat(n): print("init") a = isqrt(n) b = a b2 = pow(a, 2) - n print("a= " + str(a)) print("b= " + str(b)) print("iterate") i = 0 while True: if b2 == pow(b, 2): print("found at iteration " + str(i)) break else: a += 1 b2 = pow(a, 2) - n b = isqrt(b2) i += 1 print("iteration=" + str(i)) print("a= " + str(a)) print("b= " + str(b)) p = a + b q = a - b return p, q
def euler(self, n): if n % 2 == 0: return (n / 2, 2) if n > 2 else (2, 1) end = isqrt(n) a = 0 solutionsFound = [] firstb = -1 while a < end and len(solutionsFound) < 2: bsquare = n - a ** 2 if bsquare > 0: b = isqrt(bsquare) if (b ** 2 == bsquare) and (a != firstb) and (b != firstb): firstb = b solutionsFound.append([int(b), a]) a += 1 if len(solutionsFound) < 2: print(str(n) + "is of the form 4k+3") return -1 print("SolutionsFound:" + str(solutionsFound)) a = solutionsFound[0][0] b = solutionsFound[0][1] c = solutionsFound[1][0] d = solutionsFound[1][1] print("aˆ2+bˆ2:" + str(a ** 2 + b ** 2) + "=cˆ2+dˆ2:" + str(c ** 2 + d ** 2)) k = gcd(a - c, d - b) h = gcd(a + c, d + b) m = gcd(a + c, d - b) l = gcd(a - c, d + b) n = (k ** 2 + h ** 2) * (l ** 2 + m ** 2) print(n / 4) print(k, h, m, l) return [int(k ** 2 + h ** 2) // 2, int(l ** 2 + m ** 2) // 2]
def runPart3(N): A2 = add(isqrt(mul(24, N)), 1) x2 = isqrt(sub(mul(A2, A2), mul(24, N))) p = div(sub(A2, x2), 6) q = div(add(A2, x2), 4) return p, q
def q4(): c = mpz('22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540') n = mpz('17976931348623159077293051907890247336179769789423065727343008115' + '77326758055056206869853794492129829595855013875371640157101398586' + '47833778606925583497541085196591615128057575940752635007475935288' + '71082364994994077189561705436114947486504671101510156394068052754' + '0071584560878577663743040086340742855278549092581') e = mpz(65537) a = isqrt(n) + 1 x = isqrt(a**2 - n) p = a - x q = a + x fi = (p-1) * (q-1) d = invert(e, fi) r = powmod(c, d, n) m = digits(r, 16).split('00')[1] return m.decode('hex')
def fermat(n): print("init") a = isqrt(n) b = a b2_approx = pow(a, 2) - n print("a=" + str(a)) print("b=" + str(b)) print("main cycle") i = 0 while True: if b2_approx == pow(b, 2): print("Fount at iteration " + str(i)) break else: a += 1 b2_approx = pow(a, 2) - n b = isqrt(b2_approx) i += 1 print("iteration " + str(i)) print("a=" + str(a)) print("b=" + str(b)) p = a + b q = a - b return p, q
def q4(): c = mpz( '22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540' ) n = mpz( '17976931348623159077293051907890247336179769789423065727343008115' + '77326758055056206869853794492129829595855013875371640157101398586' + '47833778606925583497541085196591615128057575940752635007475935288' + '71082364994994077189561705436114947486504671101510156394068052754' + '0071584560878577663743040086340742855278549092581') e = mpz(65537) a = isqrt(n) + 1 x = isqrt(a**2 - n) p = a - x q = a + x fi = (p - 1) * (q - 1) d = invert(e, fi) r = powmod(c, d, n) m = digits(r, 16).split('00')[1] return m.decode('hex')
def factor_scan(N): A = gmpy2.isqrt(N) + 1 while True: x = gmpy2.isqrt(A * A - N) if gmpy2.f_mod(N, A - x) == 0: return (A - x, A + x) A += 1
def fermat_factor(n): """ Fermat's factorization method Args: n (int): target Returns: int: factor References: - https://www.geeksforgeeks.org/fermats-factorization-method - https://en.wikipedia.org/wiki/Fermat%27s_factorization_method """ if gmpy2.is_square(n): tmp = int(gmpy2.isqrt(n)) return tmp a = gmpy2.isqrt(n) b = a**2 - n while not gmpy2.is_square(b): b += 2 * a + 1 a += 1 b_sqrt = gmpy2.isqrt(b) return int(a - b_sqrt)
def find_p_q(n): t = int(isqrt(n)) + 1 possible_sqr = t**2 - n while not is_square(possible_sqr): t += 1 d = int(isqrt(possible_sqr)) return int(t - d), int(t + d)
def create_keypair(size): while True: p = get_prime(size // 2) q = get_prime(size // 2) if q < p < 2*q: break N = p * q phi_N = (p - 1) * (q - 1) # Recall that: d < (N^(0.25))/3 max_d = c_div(isqrt(isqrt(N)), 3) max_d_bits = max_d.bit_length() - 1 while True: d = urandom.getrandbits(max_d_bits) try: e = int(gmpy2.invert(d, phi_N)) except ZeroDivisionError: continue if (e * d) % phi_N == 1: break assert test_key(N, e, d) return N, e, d, p, q
def Q1Q4(): N = mpz('17976931348623159077293051907890247336179769789423065727343008115\ 77326758055056206869853794492129829595855013875371640157101398586\ 47833778606925583497541085196591615128057575940752635007475935288\ 71082364994994077189561705436114947486504671101510156394068052754\ 0071584560878577663743040086340742855278549092581') A = isqrt(N) + 1 x = isqrt(sub(mul(A, A), N)) p = sub(A, x) q = add(A, x) print("Q1:") print(p) fiN = mul(sub(p, 1), sub(q, 1)) e = mpz(65537) d = gmpy2.invert(e, fiN) ct = mpz('22096451867410381776306561134883418017410069787892831071731839143\ 67613560012053800428232965047350942434394621975151225646583996794\ 28894607645420405815647489880137348641204523252293201764879166664\ 02997509188729971690526083222067771600019329260870009579993724077\ 458967773697817571267229951148662959627934791540') pt = gmpy2.powmod(ct, d, N) ptstr = pt.digits(16) pos = ptstr.find('00') payload = ptstr[pos + 2:] print("Q4:") print(binascii.unhexlify(payload))
def factor(N): N = gmpy2.mpz(N) A = gmpy2.isqrt(N) + 1 # 这里得用isqrt,用sqrt的话返回的是一个合理的mpfr值 x = gmpy2.isqrt(A ** 2 - N) p = A - x q = A + x return p, q
def close_factor(n, b): # approximate phi phi_approx = n - 2 * isqrt(n) + 1 # create a look-up table look_up = {} z = 1 for i in range(0, b + 1): look_up[z] = i z = (z * 2) % n # check the table mu = invert(pow(2, phi_approx, n), n) fac = pow(2, b, n) for i in range(0, b + 1): if mu in look_up: phi = phi_approx + (look_up[mu] - i * b) break mu = (mu * fac) % n else: return None m = n - phi + 1 roots = ((m - isqrt(m**2 - 4 * n)) // 2, (m + isqrt(m**2 - 4 * n)) // 2) assert roots[0] * roots[1] == n return roots
def factor_n1(): ''' Factoring challenge #1: The following modulus N is a products of two primes p and q where |p−q| < 2N^(1/4). Find the smaller of the two factors and enter it as a decimal integer. ''' N = gmpy2.mpz( '179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581' ) A = gmpy2.add(gmpy2.isqrt(N), one) x = gmpy2.isqrt(gmpy2.sub(gmpy2.mul(A, A), N)) print 'Calculating first factors...' ticks = 0 while True: p = gmpy2.sub(A, x) q = gmpy2.add(A, x) if gmpy2.is_prime(p) and gmpy2.is_prime(q) and gmpy2.mul(p, q) == N: print "p =", p, "q =", q, "ticks =", ticks return else: x = gmpy2.add(x, one) ticks += 1 if ticks % 10000 == 0: print 'ticks:', ticks
def calc_near6(self): """ Solves the Extra Credit question Q3 See: Uses only integer arithmetic to avoid issues with rounding errors Solution credit to Francois Degros: https://class.coursera.org/crypto-011/forum/thread?thread_id=517#post-2279 :return: the prime factors of ```self.n```, p and q :rtype: tuple """ # A = ceil(sqrt(24 N)) - the use of isqrt() won't matter, as we seek the ceil A = add(isqrt(mul(self.n, mpz(24))), mpz(1)) # D = A^2 - 24 N D = sub(mul(A, A), mul(24, self.n)) # E = sqrt(D) - note D is a perfect square and we can use integer arithmetic E = isqrt(D) assert sub(mul(E, E), D) == mpz(0) p = div(sub(A, E), 6) q = div(add(A, E), 4) if self._check_sol(p, q): return p, q # The above is the right solution, however, there is another possible solution: p = div(add(A, E), 6) q = div(sub(A, E), 4) if self._check_sol(p, q): return p, q print 'Could not find a solution' return 0, 0
def create_keypair(size): while True: p = get_prime(size // 2) q = get_prime(size // 2) if q < p < 2 * q: break N = p * q phi_N = (p - 1) * (q - 1) # Recall that: d < (N^(0.25))/3 max_d = c_div(isqrt(isqrt(N)), 3) max_d_bits = max_d.bit_length() - 1 while True: d = urandom.getrandbits(max_d_bits) try: e = int(gmpy2.invert(d, phi_N)) except ZeroDivisionError: continue if (e * d) % phi_N == 1: break assert test_key(N, e, d) return N, e, d, p, q
def factor_N3(N): '''Factor in correctly genrated N, which is a product of two relatively close primes p/q such that, |3p-2q| < N^(1/4)''' N = mpz(N) M = 2*gmpy2.isqrt(6*N)+1 # M = (3p+2q) # M = (3p+2q) # x = (3p-2q) x = gmpy2.isqrt(M*M - 24*N) # X = (3p-2q) # since p,q is not symmetric around M/2, we need to consider two cases p1 = (M+x)/6 q1 = (M-x)/4 p2 = (M-x)/6 q2 = (M+x)/4 if gmpy2.is_prime(p1) and gmpy2.is_prime(q1) and p1*q1 == N: if p1<q1: return p1,q1 else: return q1,p1 if gmpy2.is_prime(p2) and gmpy2.is_prime(q2) and p2*q2 == N: if p2<q2: return p2,q2 else: return q2,p2 return 0
def ch3_factor(N): """ Valid when |3p - 2q| < N^(1/4) """ A = ceil_sqrt(6 * N) # let M = (3p+2q)/2 # M is not an integer since 3p + 2q is odd # So there is some integer A = M + 0.5 and some integer i such that # 3p = M + i - 0.5 = A + i - 1 # and # 2q = M - i + 0.5 = A - i # # N = pq = (A-i)(A+i-1)/6 = (A^2 - i^2 - A + i)/6 # So 6N = A^2 - i^2 - A + i # i^2 - i = A^2 - A - 6N # Solve using the quadratic equation! a = mpz(1) b = mpz(-1) c = -(A**2 - A - 6 * N) det = b**2 - 4 * a * c roots = (div(-b + isqrt(b**2 - 4 * a * c), 2 * a), div(-b - isqrt(b**2 - 4 * a * c), 2 * a)) for i in roots: if i >= 0: f = check_ch3(i, A, N) if f: return f # We should have found the root assert (False)
def close_factor(n, b): # approximate phi phi_approx = n - 2 * gmpy2.isqrt(n) + 1 # create a look-up table look_up = {} z = 1 for i in range(0, b + 1): look_up[z] = i z = (z * 2) % n # check the table mu = gmpy2.invert(pow(2, phi_approx, n), n) fac = pow(2, b, n) j = 0 while True: mu = (mu * fac) % n j += b if mu in look_up: phi = phi_approx + (look_up[mu] - j) break if j > b * b: return m = n - phi + 1 roots = (m - gmpy2.isqrt(m ** 2 - 4 * n)) // 2, \ (m + gmpy2.isqrt(m ** 2 - 4 * n)) // 2 return roots
def fermat(n): print("init") a = isqrt(n) b = isqrt(n) x = pow(a, 2) - n print("a = " + str(a)) print("b = " + str(b)) # print("x = " + str(x)) print("cycle") while True: if x == pow(b, 2): print("found") break else: a += 1 x = pow(a, 2) - n b = isqrt(x) print("a = " + str(a)) print("b = " + str(b)) # print("x = " + str(x)) print("delta = " + str(n - pow(a, 2) + pow(b, 2))) p = a + b q = a - b # assert n == p * q return p, q
def factor_N3(N): '''Factor in correctly genrated N, which is a product of two relatively close primes p/q such that, |3p-2q| < N^(1/4)''' N = mpz(N) M = 2 * gmpy2.isqrt(6 * N) + 1 # M = (3p+2q) # M = (3p+2q) # x = (3p-2q) x = gmpy2.isqrt(M * M - 24 * N) # X = (3p-2q) # since p,q is not symmetric around M/2, we need to consider two cases p1 = (M + x) / 6 q1 = (M - x) / 4 p2 = (M - x) / 6 q2 = (M + x) / 4 if gmpy2.is_prime(p1) and gmpy2.is_prime(q1) and p1 * q1 == N: if p1 < q1: return p1, q1 else: return q1, p1 if gmpy2.is_prime(p2) and gmpy2.is_prime(q2) and p2 * q2 == N: if p2 < q2: return p2, q2 else: return q2, p2 return 0
def fermat_factor(num): """ Implements Fermat's Factoring Algorithm. Implemented recursively because just one call will produce two factors, only one of which is prime. Uses a primality test as one of the base cases. Example: >>> fermat_factor(1723) [1723] >>> fermat_factor(1729) [13, 7, 19] """ if num < 2: return [] elif num % 2 == 0: return [2] + fermat_factor(num // 2) elif gmpy2.is_prime(num): return [num] a = gmpy2.isqrt(num) b2 = gmpy2.square(a) - num while not gmpy2.is_square(b2): a += 1 b2 = gmpy2.square(a) - num p = int(a + gmpy2.isqrt(b2)) q = int(a - gmpy2.isqrt(b2)) # Both p and q are factors of num, but neither are necessarily prime factors. # The case where p and q are prime is handled by the recursion base case. return fermat_factor(p) + fermat_factor(q)
def runPart1(N): A = isqrt(N) A = add(A, 1) #couldn't find default ceil function x = isqrt(sub(mul(A,A), N)) p = sub(A, x) q = add(A, x) return p, q
def fermat_factors(n): assert n % 2 != 0 a = gmpy2.isqrt(n) b2 = gmpy2.square(a) - n while not gmpy2.is_square(b2): a += 1 b2 = gmpy2.square(a) - n return a + gmpy2.isqrt(b2), a - gmpy2.isqrt(b2)
def encrypt(plaintext, publicKey): q = mpz(publicKey.q) h = mpz(publicKey.h) m = data_to_int(plaintext) assert (m < isqrt(q / 4) and m > 0) r = generate_ephemeral_key(q) assert (r < isqrt(q / 2) and r > 0) e = (r * h + m) % q return int_to_data(e)
def unpair(z: int) -> (int, int): assert z >= 0 x: int = z - gmpy2.square(gmpy2.isqrt(z)) w: int = gmpy2.isqrt(z) if x < w: return x, w else: y: int = x - w return w, y
def three(): N = mpz('720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929') A = mul(isqrt(mul(6,N)),2) A = add(A,1) x = isqrt(sub(mul(A,A),mul(24,N))) p = t_div(sub(A,x),6) q = t_div(add(A,x),4) if mul(p,q) == N: print "3. " + str(p)
def encrypt(plaintext, publicKey): q = mpz(publicKey.q) h = mpz(publicKey.h) m = data_to_int(plaintext) assert(m < isqrt(q/4) and m > 0) r = generate_ephemeral_key(q) assert(r < isqrt(q/2) and r > 0) e = (r*h + m) % q return int_to_data(e)
def minx(D): x = isqrt(D) zero = mpz(0) while 1: ysq, rem = t_divmod(x*x - 1,D) if rem == zero and is_square(ysq): print(x, isqrt(ysq)) return x x += 1
def facto(n): assert n % 2 != 0 a = gmpy2.isqrt(n) b2 = gmpy2.square(a) - n while not gmpy2.is_square(b2): a += 1 b2 = gmpy2.square(a) - n p = a + gmpy2.isqrt(b2) q = a - gmpy2.isqrt(b2) return int(p), int(q)
def factor_1(N): A = gmpy2.isqrt(N) + 1 x = gmpy2.isqrt(A*A - N) p = A - x q = A + x if p*q == N: return p, q else: return None
def factor_3(N): B = gmpy2.isqrt(24*N) + 1 x = gmpy2.isqrt(B**2 - 24*N) p = (B - x)/6 q = (B + x)/4 if p*q == N: return p, q else: return None
def q1(): n = mpz('17976931348623159077293051907890247336179769789423065727343008115' + '77326758055056206869853794492129829595855013875371640157101398586' + '47833778606925583497541085196591615128057575940752635007475935288' + '71082364994994077189561705436114947486504671101510156394068052754' + '0071584560878577663743040086340742855278549092581') a = isqrt(n) + 1 return a - isqrt(a**2 - n)
def factor_fermat(n): assert n % 2 != 0 a = gmpy2.isqrt(n) b2 = gmpy2.square(a) - n while not gmpy2.is_square(b2): a += 1 b2 = gmpy2.square(a) - n p = a + gmpy2.isqrt(b2) q = a - gmpy2.isqrt(b2) return long(p), long(q)
def one(): N = mpz('179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581') A = isqrt(N) A = add(A,1) x = isqrt(sub(mul(A,A),N)) p = sub(A,x) q = add(A,x) if mul(p,q) == N: print "1. " + str(p) return p, q, N
def fermat(n): a = int(gmpy2.ceil(gmpy2.isqrt(n))) b2 = (a**2) - n step = 0 while not gmpy2.is_square(b2): a += 1 b2 = (a**2) - n step += 1 print(n, step, a, b2) return a - gmpy2.isqrt(b2), a + gmpy2.isqrt(b2)
def RSA_fact_close_pq(N): n = gmpy2.mpz(N) a = gmpy2.isqrt(n) + 1 while a < n: p = int(a - gmpy2.isqrt(a**2 - N)) q = int(a + gmpy2.isqrt(a**2 - N)) if p * q == N: return p, a = a + 1 return None, None
def fermat_factors(n): assert n % 2 != 0 a = isqrt(n) b2 = square(a) - n while not is_square(b2): a += 1 b2 = square(a) - n factor1 = a + isqrt(b2) factor2 = a - isqrt(b2) return int(factor1), int(factor2)
def factor(N): """ :param N: 123412421.... :return: mpz(p), mpz(q) """ N = gmpy2.mpz(N) A = gmpy2.isqrt(N) + 1 # 这里得用isqrt,用sqrt的话返回的是一个合理的mpfr值 x = gmpy2.isqrt(A ** 2 - N) p = A - x q = A + x return p, q
def two(): N = mpz('648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877') A = isqrt(N) while True: A = add(A,1) x = isqrt(sub(mul(A,A),N)) p = sub(A,x) q = add(A,x) if mul(p,q) == N: print "2. " + str(p) break
def factor_scan_32(N): dA = gmpy2.isqrt(4 * 6 * N) + 1 while True: x = gmpy2.isqrt(dA * dA - 24 * N) p1 = (dA + x) / 6 if gmpy2.f_mod(N, p1) == 0: return ordered_factors(p1, N / p1) p2 = (dA - x) / 6 if gmpy2.f_mod(N, p2) == 0: return ordered_factors(p2, N / p2) dA += 1
def fermat(n): assert n % 2 == 1 if is_square(n) == 1: return isqrt(n) isqrtn = isqrt(n) b2 = (isqrtn + 1)**2 - n for a in range(isqrtn + 1, (n + 9)//6 + 2): if is_square(b2): return a - isqrt(b2) b2 = b2 + 2*a + 1 return -1 # We have a prime number
def part4(): e = gmpy2.mpz(65537) a = gmpy2.isqrt(N) + 1 x = gmpy2.isqrt(a**2 - N) p = a - x q = a + x fi = (p - 1) * (q - 1) d = gmpy2.invert(e, fi) r = gmpy2.powmod(C, d, N) m = gmpy2.digits(r, 16).split('00')[1] return bytearray.fromhex(m).decode()
def factor(n): avg_guess = gmpy2.isqrt(n) + (0 if gmpy2.is_square(n) else 1) while True: x = gmpy2.isqrt(avg_guess ** 2 - n) p = avg_guess - x q = avg_guess + x if (p * q == n): break else: avg_guess += 1 return (p, q)
def fermat(self, n): """Fermat attack""" a = b = isqrt(n) b2 = (a**2) - n while (b**2) != b2: a += 1 b2 = (a**2) - n b = isqrt(b2) p, q = (a + b), (a - b) assert n == p * q return p, q
def solve_second(N): gmpy2.get_context().precision = 1000 Nsqrt = gmpy2.isqrt(N) for A in range(Nsqrt , Nsqrt+2**20): A2 = A*A diff = A2 - N if diff > 0: possible_x = gmpy2.isqrt(A2 - N) if (A-possible_x) * (A+possible_x) == N: print "#2 ----> P is: " + str(A-possible_x) break else: print "Error: P not found!"
def find_factors(n): a = gmp.isqrt(n) p = 0 q = 0 while not check(n, p, q): a = gmp.add(a, 1) a2 = gmp.mul(a, a) x = gmp.isqrt(gmp.sub(a2, n)) p = gmp.mpz(gmp.sub(a, x)) q = gmp.mpz(gmp.add(a, x)) return (p, q)
def runPart2(N): A = isqrt(N) maxVal = add(isqrt(N), 2**20) p = 0 q = 0 while mul(p, q) != N and A <= maxVal: A = add(A, 1) x = isqrt(sub(mul(A,A), N)) p = sub(A, x) q = add(A, x) return p, q
def factor(N): """ :param N: mpz(6) :return : mpz(p), mpz(q) """ N = gmpy2.mpz(N) for i in range(1, 2 ** 20): A = gmpy2.isqrt(N) + i # 注意i得从1开始,0会报错,原因未知 x = gmpy2.isqrt(A ** 2 - N) p = A - x q = A + x if p * q == N: return p, q
def factorize(number, delta): for i in xrange(1, delta + 1): square_root = isqrt(number) average = square_root + i average_squared = mul(average, average) x = isqrt(average_squared - number) p = (average - x) q = (average + x) if mul(p, q) == number: return (p, q, i) return (0, 0, 0)
def challenge1 (N): """Factor N=p*q where abs(p-q) < 2*N**(1/4)""" N = mpz(N) A = isqrt(N) while 1: # A = (p+q)/2 is also ceil(sqrt(N)) indeed (A-sqrt(N)) < 1 # x integer such that p = A - x, q = A + x; x = sqrt(A*A - N) if pow(A, 2) > N: x = isqrt(pow(A, 2) - N) p = A - x q = A + x if ((mul(p,q) == N) and is_prime(p) and is_prime(q)): return (p,q) A = A + 1
def find_factors_6n(n): n24 = gmp.mul(n, 24) a = gmp.isqrt(n24) p = 0 q = 0 while not check(n, p, q): a = gmp.add(a, 1) a2 = gmp.mul(a, a) x = gmp.isqrt(gmp.sub(a2, n24)) p = gmp.mpz(gmp.div(gmp.sub(a, x), 6)) q = gmp.mpz(gmp.div(gmp.add(a, x), 4)) return (p, q)
def factor_2(N): initial_A = gmpy2.isqrt(N) A = initial_A upper_bound = pow(2, 20) while A - initial_A < upper_bound: A += 1 x = gmpy2.isqrt(A**2 - N) p = A - x q = A + x if p*q == N: return p, q return None
def q3(): n = gmpy2.mpz('72006226374735042527956443552558373833808445147399984182665305798191' + '63556901883377904234086641876639384851752649940178970835240791356868' + '77441155132015188279331812309091996246361896836573643119174094961348' + '52463970788523879939683923036467667022162701835329944324119217381272' + '9276147530748597302192751375739387929') a_ = gmpy2.isqrt(n * 24) + 1 d = (a_**2) - 24*n assert d > 0 p = (a_ - gmpy2.isqrt(d)) / 6 return min(p, n/p)
def fermat_factoring(N, trial = 1 << 32): """Perform Fermat's factorization. :param N: number to factorize. :param trial: (optional) maximum trial number. """ x = gmpy2.isqrt(N) + 1 y = x * x - N for i in xrange(trial): if gmpy2.is_square(y): y = gmpy2.isqrt(y) return (x + y,x - y) y += (x << 1) + 1 x += 1 # Failed return None
def solve_first(N): gmpy2.get_context().precision = 1000 Nsqrt = gmpy2.sqrt(N) A = gmpy2.mpz(gmpy2.rint_ceil(Nsqrt)) A2 = A*A x = gmpy2.isqrt(A2 - N) print "#1 ----> P is: " + str(A-x)