def Fermat(n): a = gmpy2.isqrt_rem(n)[0] + 1 b = a**2 - n while 1: q = gmpy2.isqrt_rem(b) if q[1] == 0: return a - q[0] a += 1 b = a**2 - n
def count_fair(a, b, disp=False): count = 0 a2, t = g2.isqrt_rem(a) if t != 0: a2 += 1 b2, t = g2.isqrt_rem(b) for p in iter_p(a2, b2): if is_pali((p * p).digits()): if disp: print count + 1, (p * p).num_digits(), p, p * p count += 1 return count
def attack1(N): """ |p-q|<2N^(1/4) """ A, r = gmpy2.isqrt_rem(N) if (r > 0): A += 1 x, r = gmpy2.isqrt_rem(A * A - N) if (r > 0): x += 1 if (N % (A - x) == 0 and N % (A + x) == 0): print("Factors are ", A - x, A + x) return A - x, A + x
def attack3(N): """ |3p-2q|<N^(1/4) """ N *= 4 A, r = gmpy2.isqrt_rem(6 * N) if (r > 0): A += 1 x, r = gmpy2.isqrt_rem(A * A - 6 * N) if (r > 0): x += 1 if (N % div(A - x, 6) == 0 and N % div(A + x, 4) == 0): print("Factors are ", div(A - x, 6), div(A + x, 4))
def attack2(N): """ |p-q|<2^11 N^(1/4) """ sqrtN, _ = gmpy2.isqrt_rem(N) if _ > 0: sqrtN += 1 for i in range(sqrtN, sqrtN + pow(2, 20) + 10): x, r = gmpy2.isqrt_rem(i * i - N) if (r > 0): x += 1 if (N % (i - x) == 0 and N % (i + x) == 0): print("Factors are ", i - x, i + x) break
def counf_fs(a, b): ((sa, ta), (sb, tb)) = (gmpy2.isqrt_rem(mpz(a)), gmpy2.isqrt_rem(mpz(b))) if (ta == 0): min_root = sa else: min_root = sa + 1 max_root = sb root_pals = [] for i in xrange(min_root, max_root + 1): if is_pal(str(i)): root_pals.append(i) num_fs = 0 for root_pal in root_pals: if is_pal(str(mpz(root_pal) * mpz(root_pal))): num_fs += 1 return num_fs
def solve(a, b): startx = gmpy2.isqrt_rem(a) endx = gmpy2.isqrt_rem(b) start = startx[0] if startx[1] == 0 else startx[0] + 1 end = gmpy2.mpz(endx[0]) tja = 0 ye = gmpy2.mpz(start) while ye <= end: if ispalindrome(ye) and ispalindrome(ye * ye): tja += 1 ye += 1 return tja
def factor_3(N): ''' premise: sqrt(6N) is close to (3p + 2q)/2 M = (3p + 2q)/2 is a midpoint of (3p, 2q). Note that since both p and q are odd, A = M + 0.5 is an integer. There exits an integer x such that min(3p, 2q) = A - x - 1 max(3p, 2q) = A + x It follows; N = pq = (A-x-1)(A+x)/6 = (A^2 - x^2 - A - x)/6 => 6N = A^2 - x^2 - A - x => x^2 + x + (-A^2 + A + 6N) = 0 We can obtain once from A and N via quadratic formula. ''' A, remainder = gmpy2.isqrt_rem(6*N) if remainder != mpz(0): A += 1 factors = verify_A3(A, N) if factors: return factors else: assert False, 'Failed'
def factoring_challenge_3(): """ Given |3p - 2q| < N^(1/4) and considering A = (3p + 2q) / 2 we can show that A - sqrt(6N) < 1 => A = ceil(sqrt(6N)). Let x be equal distance from A to 3p and 2q, then x = sqrt(A^2 - 6N) => we can calculate p and q based on this. """ modulus = mpz( "72006226374735042527956443552558373833808445147399984182665305798191" "63556901883377904234086641876639384851752649940178970835240791356868" "77441155132015188279331812309091996246361896836573643119174094961348" "52463970788523879939683923036467667022162701835329944324119217381272" "9276147530748597302192751375739387929" ) a, rem = gmpy2.isqrt_rem(6 * modulus) if rem > 0: a += 1 x = gmpy2.isqrt(a ** 2 - 6 * modulus) a_minus_x, a_plus_x = a - x, a + x # either p = (A - x) / 3 and q = (A + x) / 2 p, rem = gmpy2.f_divmod(a_minus_x, 3) if rem == 0: q, rem = gmpy2.f_divmod(a_plus_x, 2) if gmpy2.mul(p, q) == modulus: return p if p < q else q # or p = (A + x) / 3 and q = (A - x) / 2 p, rem = gmpy2.f_divmod(a_plus_x, 3) if rem == 0: q = gmpy2.f_div(a_minus_x, 2) if gmpy2.mul(p, q) == modulus: return p if p < q else q
def image_placer(self, directory_real): filenames = [] for i in os.listdir(directory_real): filename = os.fsdecode(i) if filename.endswith(('.jpeg', '.png', '.jpg', '.gif')): filenames.append(filename) square, rem = gmpy2.isqrt_rem(len(filenames)) fig1, axs = plt.subplots(square + 1, square + 1, dpi=300, figsize=(12, 12)) axs = axs.flatten() for i, ax in zip(filenames, axs): img = np.array(Image.open(str(directory_real) + i)) ax.axis('off') try: ax.imshow(img) except: errors.append(i) pass for i, ax in enumerate(fig1.axes): ax.tick_params(labelbottom=False, labelleft=False, bottom=False, left=False) ax.axis('off') plt.savefig('images/' + folders[count] + '.png', bbox_inches='tight') plt.close(fig1)
def factor_3(N): ''' premise: sqrt(6N) is close to (3p + 2q)/2 M = (3p + 2q)/2 is a midpoint of (3p, 2q). Note that since both p and q are odd, A = M + 0.5 is an integer. There exits an integer x such that min(3p, 2q) = A - x - 1 max(3p, 2q) = A + x It follows; N = pq = (A-x-1)(A+x)/6 = (A^2 - x^2 - A - x)/6 => 6N = A^2 - x^2 - A - x => x^2 + x + (-A^2 + A + 6N) = 0 We can obtain once from A and N via quadratic formula. ''' A, remainder = gmpy2.isqrt_rem(6 * N) if remainder != mpz(0): A += 1 factors = verify_A3(A, N) if factors: return factors else: assert False, 'Failed'
def sqrt_test(N): n = N while True: root, remainder = gmpy2.isqrt_rem(n) if remainder != 0: break n = root return gmpy2.is_prime(n)
def ceil_sqrt(num): """ # 参考答案写了这么一个函数,觉得挺好用的 :param num: mpz(num) :return: mpz(res) """ num = gmpy2.mpz(num) r, i = gmpy2.isqrt_rem(num) res = r + (1 if i else 0 ) return res
def factor(n): N = gmpy2.mpz(n) A, t = gmpy2.isqrt_rem(N) A = A + (1 if t else 0) X = gmpy2.isqrt(A * A - N) p = A - X q = A + X return p, q
def rangeFactor(n): N = gmpy2.mpz(n) A, t = gmpy2.isqrt_rem(N) A = A + (1 if t else 0) for i in range(2**20): A += 1 X = gmpy2.isqrt(A * A - N) p = A - X q = A + X if (p * q == N): return p, q
def factorize(N, ran): for i in ran: A = gmpy2.add(gmpy2.isqrt(N), i) Asq = gmpy2.mul(A, A) diff = gmpy2.sub(Asq, N) x = gmpy2.isqrt_rem(diff)[0] [correct, p, q] = verify(A, x, N) if (correct): print p return [p, q] print "Not Found"
def factorize(N,ran): for i in ran: A = gmpy2.add(gmpy2.isqrt(N),i) Asq = gmpy2.mul(A,A) diff = gmpy2.sub(Asq, N) x = gmpy2.isqrt_rem(diff)[0] [correct,p,q] = verify(A,x,N) if(correct): print p return [p,q] print "Not Found"
def factor_1(N): ''' premise: A - sqrt(N) < 1 ''' A, remainder = gmpy2.isqrt_rem(N) if remainder != mpz(0): A += 1 factors = verify_A(A, N) if factors: return factors else: print('Failed') return False
def challenge2(N_string): # find p an and q such that a given N = p * q # and |3p - 2q| < fourthroot_of(N) A = None N = mpz(N_string) N_times_24 = 24 * N # Get the ceiling of sqrt(N) A, r = gmpy2.isqrt_rem(N_times_24) if r > 0: A += 1 x, r = gmpy2.isqrt_rem(A**2 - N_times_24) assert r == 0 A_minus_x = A - x A_plus_x = A + x # Case 1 p, r = gmpy2.f_divmod(A_minus_x, 6) if r == 0: q, r = gmpy2.f_divmod(A_plus_x, 4) if r == 0: assert N == p * q return p.digits(), q.digits() # Case 2 p, r = gmp2.f_divmod(A_plus_x, 6) if r == 0: q, r = gmpy2.f_divmod(A_minus_x, 4) if r == 0: assert N == p * q return p.digits(), q.digits() return None, None
def break_challenge_3(N3): A = gmpy2.isqrt(6 * N3) AA = 2 * A + 1 (res, rem) = gmpy2.isqrt_rem(AA**2 - 24 * N3) (p, rem1) = gmpy2.c_divmod(res + AA, 4) (q, rem2) = gmpy2.c_divmod(res - AA, 6) if rem != 0 or rem2 != 0: (p, rem1) = gmpy2.c_divmod(res - AA, 4) (q, rem2) = gmpy2.c_divmod(res + AA, 6) assert (abs(p * q) == N3) return min(abs(p), abs(q))
def factor(N, A_min_sqrt_N_lt): sqrt_N, r = gmpy2.isqrt_rem(N) if r: # if the remainder is != 0, the sqrt is not a round number: round it sqrt_N += 1 p = q = None # try possible values for A from √N to the bigger value of (A - √N) for A in range(sqrt_N, sqrt_N + A_min_sqrt_N_lt): x = gmpy2.isqrt(pow(A, 2) - N) p = A - x q = A + x if gmpy2.mul(p, q) == N: # we found a valid value for A return p, q raise ValueError('Cannot factor p and q from modulus')
def factor_2(N): ''' premise: A - sqrt(N) < 2**20 ''' root, remainder = gmpy2.isqrt_rem(N) if remainder != mpz(0): root += 1 for i in range(2**20): if i % 5000 == 0: # print('Attempts made to find A: {}'.format(i)) pass A = root + i factors = verify_A(A, N) if factors: return factors assert False, 'Failed'
def fermat_sieve(n, rounds): a = gmpy2.isqrt_rem(n)[0] valid = n % 20 Val = [0, 1, 4, 5, 9, 16] Cand = set() for i in range(10): for j in Val: if ((a - i)**2 - j) % 20 in Val: Cand.add(j) b = 0 for i in range(rounds): a_2 = a**2 b_2 = a_2 - n if b_2 % 20 in Cand: if gmpy2.is_square(b_2): b = gmpy2.iroot(b_2, 2)[0] return a - b, a + b a_min_b = int(a - b) a += 1 return None, None
def challenge3(N_string): # find p an and q such that a given N = p * q # and |p - q| < 2^11 * fourthroot_of(N) N = mpz(N_string) start = gmpy2.isqrt(N) + 1 end = start + mpz(2)**mpz(20) for A in range(start, end): A_squared_minus_N = A**2 - N x, r = gmpy2.isqrt_rem(A_squared_minus_N) if r == 0: p = A - x q = A + x if N == gmpy2.mul(p, q): return p.digits(), q.digits() return None, None
def challenge1(N_string): # find p an and q such that a given N = p * q # and |p - q| < 2 * fourthroot_of(N) A = None N = mpz(N_string) # Get the ceiling of sqrt(N) A, r = gmpy2.isqrt_rem(N) if r > 0: A += 1 A_squared_minus_N = A**2 - N x = gmpy2.isqrt(A_squared_minus_N) p = A - x q = A + x N_from_pq = gmpy2.mul(p, q) assert N == N_from_pq return p.digits(), q.digits()
def wiener_attack(N, e): """Perform Wiener's attack. :param N: RSA public key N. :param e: RSA public key e. """ convergents = cf_convergents(cf(e, N)) for k,d in convergents: if k == 0 or (e * d - 1) % k != 0: continue phi = (e * d - 1) / k c = N - phi + 1 # now p,q can be the root of x**2 - s*x + n = 0 det = c * c - 4 * N if not det >= 0: continue s, r = gmpy2.isqrt_rem(det) if r == 0 and gmpy2.is_even(c + s): return (d, (c + s) / 2,(c - s) / 2) # Failed return None
def threeFactor(n): N = gmpy2.mpz(n) A, t = gmpy2.isqrt_rem(6 * N) A = A + (1 if t else 0) a = gmpy2.mpz(1) b = gmpy2.mpz(-1) c = -(A**2 - A - 6 * N) quadratic = b**2 - 4 * a * c roots = (gmpy2.div(-b + gmpy2.isqrt(quadratic), 2 * a), gmpy2.div(-b - gmpy2.isqrt(quadratic), 2 * a)) for root in roots: if root >= 0: p, q = (gmpy2.div(A + root - 1, 3), gmpy2.div(A - root, 2)) if (p * q == N): return p, q p, q = (gmpy2.div(A - root, 3), gmpy2.div(A + root - 1, 2)) return p, q
def wiener_attack(N, e): """Perform Wiener's attack. :param N: RSA public key N. :param e: RSA public key e. """ convergents = cf_convergents(cf(e, N)) for k, d in convergents: if k == 0 or (e * d - 1) % k != 0: continue phi = (e * d - 1) // k c = N - phi + 1 # now p,q can be the root of x**2 - s*x + n = 0 det = c * c - 4 * N if not det >= 0: continue s, r = gmpy2.isqrt_rem(det) if r == 0 and gmpy2.is_even(c + s): return (d, (c + s) // 2, (c - s) // 2) # Failed return None
def factoring_challenge_2(): """ |p - q| < 2^11 * N^(1/4) in this case: A - sqrt(N) < 2^20 """ modulus = mpz( "6484558428080716696628242653467722787263437207069762630604390703787" "9730861808111646271401527606141756919558732184025452065542490671989" "2428844841839353281972988531310511738648965962582821502504990264452" "1008852816733037111422964210278402893076574586452336833570778346897" "15838646088239640236866252211790085787877" ) a = gmpy2.isqrt(modulus) + 1 while True: x, rem = gmpy2.isqrt_rem(a ** 2 - modulus) if rem == 0: p, q = a - x, a + x if gmpy2.mul(p, q) == modulus: return p a += 1
def factoring_challenge_1(): """ By following assumption that |p - q| < 2N^(1/4), it can be shown that A - sqrt(N) < 1, where A = (p + q)/2. A is an integer, hence A = ceil(sqrt(N)). x is an integer such that p = A - x and q = A + x. It can be shown that x = sqrt(A^2 - N). Now, given x and A we can factor N by computing p and q. """ modulus = mpz( "17976931348623159077293051907890247336179769789423065727343008115" "77326758055056206869853794492129829595855013875371640157101398586" "47833778606925583497541085196591615128057575940752635007475935288" "71082364994994077189561705436114947486504671101510156394068052754" "0071584560878577663743040086340742855278549092581" ) a, rem = gmpy2.isqrt_rem(modulus) if rem > 0: a += 1 x = gmpy2.isqrt(a ** 2 - modulus) p, q = a - x, a + x assert gmpy2.mul(p, q) == modulus return p
def ceil_sqrt(x): s,t = isqrt_rem(x) return s + (1 if t else 0)
N: {0} A: {1} x: {2} p: {3} q: {4} N - p * q: {5}""".format(N, A, x, p, q, N - p * q) print msg # ======================================== # Factoring challenge 1: N = mpz( 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 ) data = gmpy2.isqrt_rem(N) A = data[0] + 1 x, r = gmpy2.isqrt_rem(A**2 - N) assert (r == 0) print_result("challenge 1", N, A, x) # ======================================== # no 2: N = mpz( 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 ) isqrtN, _ = gmpy2.isqrt_rem(N) A = None
__author__ = "bbyk" import gmpy2, codecs from gmpy2 import mpz N = mpz( "179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581" ) SNr = gmpy2.isqrt_rem(N) A = SNr[0] if SNr[1] > 0: A += 1 assert gmpy2.mul(A, A) > N a_n = gmpy2.mul(A, A) - N Xr = gmpy2.isqrt_rem(a_n) assert Xr[1] == 0 p = A - Xr[0] q = A + Xr[0] assert gmpy2.mul(p, q) == N print(p) ct = mpz( "22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540" ) e = mpz(65537) fN = N - p - q + 1 d = gmpy2.invert(e, fN)
#!/usr/bin/env python3 from gmpy2 import isqrt, isqrt_rem, mpz, invert, powmod N = mpz( 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 ) ct = mpz( 22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540 ) s, t = isqrt_rem(N) A = s + (1 if t > 0 else 0) x = isqrt(A**2 - N) p = A - x q = A + x phi_N = (p - 1) * (q - 1) d = invert(65537, phi_N) # divm(phi_N + 1, 65537, phi_N) pt = hex(powmod(ct, d, N)) print(bytes.fromhex(pt[pt.find('00') + 2:]))
#!/usr/bin/env python3 ''' A = (3p+2q)/2, A is rational number A²-6N = (3p-2q)²/4 > 0, A > √6N A-√6N = (A²-6N)/(A+√6N) = (3p-2q)⁴/4(A+√6N) < (3p-2q)⁴/8√6N < √N/8√6N < 1 2A-2√6N = 2A-√24N < 1/4√6 < 1 6p = 2A - x 4q = 2A + x 24N = 24pq = (2A)² - x², x = √((2A)² - 24N) ''' from gmpy2 import isqrt, mpz, isqrt_rem, div N = mpz(720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929) s, t = isqrt_rem(24 * N) A2 = s + (1 if t > 0 else 0) x = isqrt(A2 ** 2 - 24 * N) print(div(A2 - x, 6))
return Xdigits == Ydigits ################################## #f = open('C-small-practice.in', 'r') f = open('C-small.in', 'r') #f = open('C-large.in', 'r') fw = open('C.out', 'w') lines = f.readlines() T = int(lines.pop(0)) for i in xrange(T): print '----------', i + 1 FandSCount = 0 A, B = map(lambda x: gmpy2.mpz(x), lines.pop(0).split(' ')) (Asqrt, rem) = gmpy2.isqrt_rem(A) if rem > 0: Asqrt += 1 #Adigits = [x for x in gmpy2.digits(A)] Xdigits = NextBiggerPalindrome(gmpy2.digits(Asqrt)) X2 = gmpy2.mpz(Xdigits)**2 while X2 <= B: #print X2 FandSCount += IsPalindrome(X2) Xdigits = NextPalindrome(Xdigits) X2 = gmpy2.mpz(Xdigits)**2 Output(i + 1, FandSCount) #print IsPalindrome(1234321