def FermatFactAlg(n): """ Fermat's factoring algorithm 2.5.3 p 196 """ n = gmpy.mpz(n) if n % 2 == 0: print("%d is even" % n) # gmpy.sqrt is largest truncated sqrt # k = int( math.sqrt(n) ) + 1 k = gmpy.sqrt(n) + 1 y = k**2 - n d = 1 while True: # floor_sqrt_y = float( int( math.sqrt(y) ) ) floor_sqrt_y = gmpy.sqrt(y) if ((floor_sqrt_y**2)**2) == (y**2): break else: y = y + 2 * k + d d += 2 # print floor_sqrt_y, gmpy.qdiv( n, 2.0) # print ((floor_sqrt_y ** 2) ** 2), (y ** 2) if floor_sqrt_y > gmpy.qdiv(n, 2.0): print("No factor found ") return x = gmpy.sqrt(n + y) y = gmpy.sqrt(y) print(" the non-trivial factors of %d are" % n) print(" %d and %d" % (x - y, x + y))
def close_factor(n, b): # approximate phi phi_approx = n - 2 * gmpy.sqrt(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 = gmpy.invert(pow(2, phi_approx, n), n) fac = pow(2, b, n) j = 0 # do a bsgs-type attack 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 # once phi is found, we can compute the factors m = n - phi + 1 roots = (m - gmpy.sqrt(m ** 2 - 4 * n)) / 2, \ (m + gmpy.sqrt(m ** 2 - 4 * n)) / 2 return roots
def q2(): N = gmpy.mpz( "6484558428080716696628242653467722787263437207069762630604390703787 \ 9730861808111646271401527606141756919558732184025452065542490671989 \ 2428844841839353281972988531310511738648965962582821502504990264452 \ 1008852816733037111422964210278402893076574586452336833570778346897 \ 15838646088239640236866252211790085787877") A0 = gmpy.sqrt(N) + 1 for i in xrange(2**20): A = A0 + i x1 = A**2 - N if gmpy.is_square(x1): x = gmpy.sqrt(x1) p = A - x q = A + x if p * q == N: break assert p * q == N print "Answer to Question 2:" print p # Answer: assert p == gmpy.mpz( "254647961469961834380088165639739422293414542685241578463285819278857779699852 \ 22835143851073249573454107384461557193173304497244814071505790566593206419759" )
def FermatFactAlg(n): """ Fermat's factoring algorithm 2.5.3 p 196 """ n = gmpy.mpz(n) if n % 2 == 0: print("%d is even" % n) # gmpy.sqrt is largest truncated sqrt # k = int( math.sqrt(n) ) + 1 k = gmpy.sqrt(n) + 1 y = k ** 2 - n d = 1 while True: # floor_sqrt_y = float( int( math.sqrt(y) ) ) floor_sqrt_y = gmpy.sqrt(y) if ((floor_sqrt_y ** 2) ** 2) == (y ** 2): break else: y = y + 2 * k + d d += 2 # print floor_sqrt_y, gmpy.qdiv( n, 2.0) # print ((floor_sqrt_y ** 2) ** 2), (y ** 2) if floor_sqrt_y > gmpy.qdiv(n, 2): print("No factor found ") return x = gmpy.sqrt(n + y) y = gmpy.sqrt(y) print(" the non-trivial factors of %d are" % n) print(" %d and %d" % (x - y, x + y))
def q1(): N = gmpy.mpz( "17976931348623159077293051907890247336179769789423065727343008115 \ 77326758055056206869853794492129829595855013875371640157101398586 \ 47833778606925583497541085196591615128057575940752635007475935288 \ 71082364994994077189561705436114947486504671101510156394068052754 \ 0071584560878577663743040086340742855278549092581") A = gmpy.sqrt(N) + 1 x1 = A**2 - N assert gmpy.is_square(x1) x = gmpy.sqrt(x1) p = A - x q = A + x assert p * q == N print "Answer to Question 1:" print p #print q #print x # Answer: assert p == gmpy.mpz( "134078079299425970995740249982058461274793658205923933777235614437217640300736 \ 62768891111614362326998675040546094339320838419523375986027530441562135724301" ) return N, p, q
def main(): # # First part # N1 = mpz( 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 ) p, q = func1(N1) assert (p * q == N1) log.warning("Smallest factor: {0}".format(min([p, q]))) # # Second part # N2 = mpz( 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 ) # Setup ranges = create_ranges(sqrt(N2), sqrt(N2) + 2**20, 10000) producer = Process(target=_producer, args=(ranges, )) consumer = Process(target=_consumer) pool = [Process(target=_worker, args=(func2, N2)) for _ in range(NCPU)] # Compute for p in [producer, consumer] + pool: p.start() consumer.join() # Teardown producer.terminate() for p in pool: p.terminate()
def main(): # # First part # N1 = mpz(179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581) p,q = func1(N1) assert(p*q == N1) log.warning("Smallest factor: {0}".format(min([p,q]))) # # Second part # N2 = mpz(648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877) # Setup ranges = create_ranges(sqrt(N2), sqrt(N2) + 2**20, 10000) producer = Process(target=_producer, args=(ranges,)) consumer = Process(target=_consumer) pool = [Process(target=_worker, args=(func2, N2)) for _ in range(NCPU)] # Compute for p in [producer, consumer] + pool: p.start() consumer.join() # Teardown producer.terminate() for p in pool: p.terminate()
def fermat_factor(n, n1, n2): a = gmpy.sqrt(n) + 1 b = a * a - n bsq = gmpy.sqrt(b) while bsq * bsq != b or a + bsq == n1 or a + bsq == n2: a += 1 b = a * a - n bsq = gmpy.sqrt(b) return a + bsq
def fermat(N): a = gmpy.sqrt(N) b2 = a*a - N while not gmpy.is_square(gmpy.mpz(b2)): b2 += 2*a + 1 a += 1 factor1 = a - gmpy.sqrt(b2) factor2 = a + gmpy.sqrt(b2) return (long(factor1.digits()), long(factor2.digits()))
def slaves(): while True: b2 = queue.get() if b2 is None: break if gmpy.is_square(gmpy.mpz(b2)): with lock: finish.value = 1 a = gmpy.sqrt(n + b2) factor1 = a - gmpy.sqrt(b2) factor2 = a + gmpy.sqrt(b2) p.value = long(factor1.digits()) q.value = long(factor2.digits())
def factor_fermat(N): a = gmpy.sqrt(N) b2 = a * a - N tes = 0 while not gmpy.is_square(gmpy.mpz(b2)): b2 += 2 * a + 1 a += 1 tes += 1 if tes > 3000: return "x", "x" factor1 = a - gmpy.sqrt(b2) factor2 = a + gmpy.sqrt(b2) return (long(factor1.digits()), long(factor2.digits()))
def find1(N, A = None): if A == None: A = gmpy.mpz(gmpy.sqrt(N)+1) k = A*A - N assert gmpy.is_power(k) x = gmpy.sqrt(A*A - N) p, q = A - x, A + x #print p #print q assert gmpy.is_prime(p) assert gmpy.is_prime(q) assert p*q==N return p, q
def crack(n): a = gmpy.sqrt(n) while True: b2 = a * a - n if b2 <= 0: a += 1 else: b = gmpy.sqrt(b2) if b * b == b2: p = a + b q = a - b return p, q a += 1
def find1(N, A=None): if A == None: A = gmpy.mpz(gmpy.sqrt(N) + 1) k = A * A - N assert gmpy.is_power(k) x = gmpy.sqrt(A * A - N) p, q = A - x, A + x #print p #print q assert gmpy.is_prime(p) assert gmpy.is_prime(q) assert p * q == N return p, q
def q3(): N = gmpy.mpz( "72006226374735042527956443552558373833808445147399984182665305798191 \ 63556901883377904234086641876639384851752649940178970835240791356868 \ 77441155132015188279331812309091996246361896836573643119174094961348 \ 52463970788523879939683923036467667022162701835329944324119217381272 \ 9276147530748597302192751375739387929") ''' Given: |3p - 2q| < N**(1/4) (1) N = pq Let A = (3p+2q)/2 => 2A = (6p+4q)/2 => 2A is an integer, and lies exactly midway between 6p and 4q Let 6p = 2A - x 4q = 2A + x => 24pq = 4A**2 - x**2 => 24N = 4A**2 - x**2 => x = sqrt(4A**2 - 24N) (2) To find x using (2), we need to find relation between A and N. Consider the value A**2 - 6N A**2 - 6N = (3p+2q)**2 / 4 - 6pq = (3p-2q)**2 / 4 , on simplifying. But, A**2 - 6N = (A + sqrt(6N))(A - sqrt(6N)) Hence, A - sqrt(6N) = (3p-2q)**2 / (4(A + sqrt(6N))) (3) Now A = (3p+2q)/2 > sqrt(3p*2q) = sqrt(6N) since AM > GM for 2 non-equal numbers => A > sqrt(6N) => A + sqrt(6N) > 2*sqrt(6N) Using above line in (3), we get the inequality: A - sqrt(6N) < (3p-2q)**2 / (8*sqrt(6N)) < sqrt(N) / (8*sqrt(6N)) Using (1) Thus A - sqrt(6N) < 1 / (8*sqrt(6) < 1 [Proved]''' twoA = gmpy.sqrt( 4 * 6 * N ) + 1 # A = sqrt(6N) + 0.5, since A, which is (3p+2q)/2, is NOT an integer. v = (twoA**2) - 24 * N assert gmpy.is_square(v) x = gmpy.sqrt(v) p = (twoA - x) / 6 q = (twoA + x) / 4 assert p * q == N print "Answer to Question 3:" print p # Answer: assert p == gmpy.mpz( "219098495924755330922739885315839558989821760933449290300994235841272120781261 \ 50044721102570957812665127475051465088833555993294644190955293613411658629209" )
def factor_fermat(N): """ Guess at a and hope that a^2 - N = b^2, which is the case if p and q is "too close". """ a = gmpy.sqrt(N) b2 = a*a - N while not gmpy.is_square(gmpy.mpz(b2)): b2 += 2*a + 1 a += 1 factor1 = a - gmpy.sqrt(b2) factor2 = a + gmpy.sqrt(b2) return (int(factor1.digits()),int(factor2.digits()))
def could_be_prime(n): '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits. Returns whether it is possible for n to be prime (True or False). ''' if n < 2: return False if n == 2: return True if not n & 1: return False product = ONE log_n = int(math.log(n)) + 1 bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1 if bound * log_n >= n: bound = 1 log_n = int(sqrt(n)) prime_bound = 0 prime = 3 for _ in xrange(bound): p = [] prime_bound += log_n while prime <= prime_bound: p.append(prime) prime = next_prime(prime) if p != []: p = prod(p) product = (product * p) % n return gcd(n, product) == 1
def crack(self): a = gmpy.sqrt(self.n) max = a + self.limit while a < max: b2 = a * a - self.n if b2 >= 0: b = gmpy.sqrt(b2) if b * b == b2: break a += 1 if a < max: self.p = a + b self.q = a - b return True else: return False
def crack(self): a = gmpy.sqrt(self.n) max = a + self.limit while a < max: b2 = a*a - self.n if b2 >= 0: b = gmpy.sqrt(b2) if b*b == b2: break a += 1 if a < max: self.p = a+b self.q = a-b return True else: return False
def crack(solver): a = gmpy.sqrt(solver.datas["n"][-1]) max = a + 999999999 while a < max: b2 = a * a - solver.datas["n"][-1] if b2 >= 0: b = gmpy.sqrt(b2) if b * b == b2: break a += 1 if a < max: solver.addq(int(a - b)) solver.addp(int(a + b)) return True else: return False
def vector_norm_i(v): """ Calculate Norm of vector as Integer Args: v : A vector Return: || v || """ return int(gmpy.ceil(gmpy.sqrt(sum(starmap(op.pow, zip(v, cycle([2])))))))
def factors(n): result = set() n = gmpy.mpz(n) for i in range(1, gmpy.sqrt(n)+1): div, mod = gmpy.fdivmod(n, i) if not mod: result |= {gmpy.mpz(i), div} return result
def try_midpoint(N, midpoint): delta = gmpy.sqrt(midpoint * midpoint - N) p = midpoint - delta q = midpoint + delta if p * q == N: return min(p, q) else: return False
def try_midpoint(N, midpoint): delta = gmpy.sqrt(midpoint*midpoint - N) p = midpoint - delta q = midpoint + delta if p*q == N: return min(p,q) else: return False
def solve(A, B): counter = 0 for x in range(A, B + 1): if is_fair(str(x)): if gmpy.is_square(x): if is_fair(str(gmpy.sqrt(x))): counter += 1 return counter
def find4(N): A = gmpy.mpz(gmpy.sqrt(6*N)+1) while True: try: find3(N, A) return except: A = A+1 pass
def find4(N): A = gmpy.mpz(gmpy.sqrt(6 * N) + 1) while True: try: find3(N, A) return except: A = A + 1 pass
def __init__(self, size=400, *args, **kwargs): '''initializes a square playground. size must be a perfect square ''' if is_square(size): self.size = size self.length = int(sqrt(self.size)) self.set_grid() else: raise ValueError("size must be a perfect square") object.__init__(self, *args, **kwargs)
def find_close(n): sq = gmpy.sqrt(n) sq = sq - 10 if sq % 2 == 0: sq = sq - 1 for i in range(10000): sq = sq + 2 if sq == gmpy.gcd(sq, n): return sq return None
def find3(N, A=None): if A == None: A = gmpy.mpz(gmpy.sqrt(24 * N) + 1) k = A * A - 24 * N assert gmpy.is_power(k) x = gmpy.sqrt(k) print x q1 = (A - x) / 4 p1 = (A + x) / 6 q2 = (A + x) / 4 p2 = (A - x) / 6 if gmpy.is_prime(p1) and gmpy.is_prime(q1) and p1 * q1 == N: return p1, q1 elif gmpy.is_prime(p2) and gmpy.is_prime(q2) and p2 * q2 == N: return p2, q2 else: assert False
def find4(N): A = B = gmpy.mpz(gmpy.sqrt(24 * N) + 1) while True: try: return find3(N, A) except: A = A + 1 if A - B > 2**20: return False pass
def find4(N): A = B = gmpy.mpz(gmpy.sqrt(24*N)+1) while True: try: return find3(N, A) except: A = A+1 if A - B > 2**20: return False pass
def find3(N, A = None): if A == None: A = gmpy.mpz(gmpy.sqrt(24*N)+1) k = A*A - 24*N assert gmpy.is_power(k) x = gmpy.sqrt(k) print x q1 = (A - x)/4 p1 = (A + x)/6 q2 = (A + x)/4 p2 = (A - x)/6 if gmpy.is_prime(p1) and gmpy.is_prime(q1) and p1*q1==N: return p1, q1 elif gmpy.is_prime(p2) and gmpy.is_prime(q2) and p2*q2==N: return p2, q2 else: assert False
def crack(self): a = gmpy.sqrt(self.n) max = a + self.limit while a < max: b2 = a * a - self.n if b2 >= 0: b = gmpy.sqrt(b2) if b * b == b2: break a += 1 if a < max: self.p = long(a + b) self.q = long(a - b) phi = (self.p - 1) * (self.q - 1) if has_invmod(self.e, phi): self.d = long(invmod(self.e, phi)) return True else: return False
def q2(): done = False i = 0 sqrtN2 = gmpy.sqrt(N2) + 1 print "start" done = False while(i < 2**20): res = try_midpoint(N2, sqrtN2 + i) if res: done = True print(res) i += 1 print(done)
def PollardsRho(N): """ Pollard's Rho method for factoring """ from exercises import Alg_improved_Euclid as gcd from random import randint N = gmpy.mpz(N) """ generator function """ def f(x, N): return (((x ** 2) + 1) % N) t = 75 * gmpy.sqrt(N) sqrt_t = gmpy.sqrt(t) factor_found = False while not factor_found: xim1 = randint(1, gmpy.sqrt(N) / 10) # seed yim1 = f(f(xim1, N), N) i = 0 while i < sqrt_t: xi = f(xim1, N) yi = f(f(yim1, N), N) # yi = f( yim1, N ) # xi = f( f( xim1, N ), N ) # print( 'gcd( xi - yi ) = gcd( %d )' % abs(xi - yi) ) d = gcd(abs(xi - yi), N) if d != 1: print('Non trivial factor found: ', d) factor_found = True break if xi == yi % N: print('Running with new seed') break xim1 = xi yim1 = yi i += 1
def q2(): done = False i = 0 sqrtN2 = gmpy.sqrt(N2) + 1 print "start" done = False while (i < 2**20): res = try_midpoint(N2, sqrtN2 + i) if res: done = True print(res) i += 1 print(done)
def PollardsRho(N): """ Pollard's Rho method for factoring """ from exercises import Alg_improved_Euclid as gcd from random import randint N = gmpy.mpz(N) """ generator function """ def f(x, N): return (((x**2) + 1) % N) t = 75 * gmpy.sqrt(N) sqrt_t = gmpy.sqrt(t) factor_found = False while not factor_found: xim1 = randint(1, gmpy.sqrt(N) / 10) # seed yim1 = f(f(xim1, N), N) i = 0 while i < sqrt_t: xi = f(xim1, N) yi = f(f(yim1, N), N) # yi = f( yim1, N ) # xi = f( f( xim1, N ), N ) # print( 'gcd( xi - yi ) = gcd( %d )' % abs(xi - yi) ) d = gcd(abs(xi - yi), N) if d != 1: print('Non trivial factor found: ', d) factor_found = True break if xi == yi % N: print('Running with new seed') break xim1 = xi yim1 = yi i += 1
def check_range(start, end): qty = 0 i = start for i in xrange(start, end+1): if gmpy.is_square(i): strn = str(i) if strn == strn[::-1]: n = str(gmpy.sqrt(i)) if n == n[::-1]: qty += 1 i += 1 return qty
def fermat(n): stime = time.time() pool = mp.Pool() a = gmpy.sqrt(n) base = a * a - n pool.apply_async(master, args=( base, a, )) for _ in range(MAX_TASK - 1): pool.apply_async(slaves) pool.close() pool.join() etime = time.time() return (p.value, q.value)
def Factor(n, parameter): if n % 2 == 0: return true a = gmp.sqrt(n) b2 = a**2-n bound = a + parameter while not gmp.is_square(b2) and a<=bound: b2=b2+2*a+1 a+=1 if a > bound: return False else: return True
def crack(self): for cvg in cf2cvg(f2cf(self.e, self.n)): k = cvg.numerator if k == 0: continue d = cvg.denominator phi = (self.e*d-1)//k nb = self.n - phi + 1 squ = nb*nb-4*self.n if squ < 0: continue root = gmpy.sqrt(squ) if root*root == squ and not (nb+root)&1: self.p = (nb+root)>>1 self.q = (nb-root)>>1 self.d = d return True return False
def extFactor(n, parameter): def fermat(n, astart, aend, astep, k): if k==len(moduli) or (aend-astart)/astep < 2: lista = [astart+i*astep for i in range(0,((aend-astart)/astep)+1)] listb2 = [a**2 - n for a in lista] return any([gmp.is_square(b2) for b2 in listb2]) result = [] mod, quadRes = moduli[k] a = astart for i in range(0, min(mod, (aend-astart)/astep + 1)): if ((a**2-n) % mod) in quadRes: result.append(fermat(n, a, aend, astep*mod, k+1)) a+=astep return any(result) a=gmp.sqrt(n) return fermat(n,a, a+parameter, 1, 0)
def shanks(y, a, n): """ Shanks' baby-step giant-step for finding discrete logarithms of form : x = log_a ( y mod n ) """ s = gmpy.sqrt(n) S = {} # calculate the baby steps T = {} # calculate the giant steps for i in range(s): S['%s' % gmpy.mpz((y * (a ** i)) % n)] = int(i) T['%s' % gmpy.mpz((a ** ((i + 1) * s)) % n)] = int(i) # mathching and computing for key in S.keys(): if key in T: r = S[key] st = (T[key] + 1) * s break x = st - r print 'So log_%d %d\t(mod %d) =\t%d ' % (a, y, n, x) print 'or equiv. %d^%d\t(mod %d) =\t%d ' % (a, x, n, y) return x
import gmpy N = gmpy.mpz(179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581) print "N:\t\t", format(N) A = gmpy.mpz(gmpy.sqrt(N)+1) print "A:\t\t", format(A) x = gmpy.mpz(gmpy.sqrt(gmpy.mpz(A*A-N)+1)) print "x:\t\t", format(x) p = gmpy.mpz(A-x) q = gmpy.mpz(A+x) print "p: ", p
def sqrt(self): return self.mfi_(gmpy.sqrt(self.val))
# This is also for the Brown numbers project # This only outputs the number I care about. # % Brown numbers have the following properties: # % (m,n) such that: # % n!+1 = m^2 # % Paul Erdos postulated that there are only 3 sets. import math import time import gmpy n = 1000000000 start = time.time() test = gmpy.fac(n)+1 if (gmpy.sqrtrem(test))[1]==0: m = gmpy.sqrt(test) end = time.time() # Final time calculation, duplicate for legibility print 'It is a brown number!' # For legibility print 'n = ' + str(n) print 'm = ' + str(m) print 'time = ' + str(end-start) else: end = time.time() # Final time calculation, duplicate for legibility print 'Nope.' print end-start
def write_ascii_gevp(path, basename, data, verbose=1): ensure_dir(path) # Cast data into longish data format with only gevp_row and gevp_col as index data = data.T.reset_index().set_index(['cnfg', 'T']).stack( level=['gevp_row', 'gevp_col', 'p_{cm}', '\mu']).reset_index(['p_{cm}', '\mu', 'cnfg', 'T']) data[['p_x', 'p_y', 'p_z']] = data['p_{cm}'].apply(literal_eval).apply(pd.Series) del data['p_{cm}'] data.rename(columns={0: 'value', '\mu': 'alpha'}, inplace=True) gevp_indices = data.index.unique() operator_indices = data.loc[gevp_indices[0]].set_index( ['p_x', 'p_y', 'p_z', 'alpha']).index.unique() assert np.all(data.notnull()), ('Gevp contains null entires') assert gmpy.is_square(len(gevp_indices)), 'Gevp is not a square matrix' gevp_size = gmpy.sqrt(len(gevp_indices)) # Write file with physical content corresponding to gevp index number (gevp_col) gevp_elements = [i[1] for i in gevp_indices.values[:gevp_size]] np.savetxt(os.path.join(path, basename + '_gevp-indices.tsv'), np.array(zip(range(gevp_size), gevp_elements)), fmt='%s', delimiter='\t', comments='', header='id\telement') # Write file with physical content corresponding to operator (p_cm, alpha) operator_elements = np.array([tuple(i) for i in operator_indices.values]) np.savetxt( os.path.join(path, basename + '_operator-indices.tsv'), np.column_stack( (np.arange( operator_elements.shape[0]), operator_elements)), fmt='%s', delimiter='\t', comments='', header='id\tp_x\tp_y\tp_z\talpha') if verbose: print 'Creating a {} x {} Gevp from {} operators'.format( gevp_size, gevp_size, operator_elements.shape[0]) # Loop over all projected operators and gevp elements and write an ascii file for gevp_counter, gevp_index in enumerate(gevp_indices): for operator_counter, operator_index in enumerate(operator_indices): filename = os.path.join( path, basename + '_op%d_gevp%d.%d.tsv' % (operator_counter, gevp_counter / gevp_size, gevp_counter % gevp_size)) df = data.loc[gevp_index].set_index( ['p_x', 'p_y', 'p_z', 'alpha']).loc[operator_index] df.to_csv(filename, sep='\t', index=False)
def _func1(N, A): """Computes p and q based on N and A""" x = sqrt(A**2 - N) p = A - x q = A + x return p,q
def sqrt(n): return gmpy.sqrt(n)
def gevp(plotting_function, plotdata, bootstrapsize, pdfplot, logscale=False, verbose=False): """ Create a multipage plot with a page for every element of the rho gevp Parameters ---------- plotdata: pd.DataFrame Table with a row for each gevp element (sorted by gevp column running faster than gevp row) and hierarchical columns for gauge configuration number and timeslice bootstrapsize : int The number of bootstrap samples being drawn from `plotdata`. pdfplot : mpl.PdfPages object Plots will be written to the path `pdfplot` was created with. See also -------- utils.create_pdfplot() """ assert np.all(plotdata.notnull()), 'Gevp contains null entires' plotdata = mean_and_std(plotdata, bootstrapsize) # abs of smallest positive value #linthreshy = plotdata['mean'][plotdata['mean'] > 0].min().min() # abs of value closest to zero linthreshy = 1e3 * plotdata['mean'].iloc[plotdata.loc[:, ('mean', 0)].nonzero()].abs().min().min() # Create unique list of gevp elements to loop over while keeping order intact seen = set() plotlabel = [] for item in [(i[0], i[1]) for i in plotdata.index.values]: if item not in seen: seen.add(item) plotlabel.append(item) assert gmpy.is_square(len(plotlabel)), 'Gevp is not a square matrix' gevp_size = int(gmpy.sqrt(len(plotlabel))) # Prepare Figure fig, axes = plt.subplots(gevp_size, gevp_size, sharex=True, sharey=True) for counter, graphlabel in enumerate(plotlabel): if verbose: print '\tplotting ', graphlabel[0], ' - ', graphlabel[1] # Prepare Axes ax = axes[counter // gevp_size, counter % gevp_size] # ax.set_title(r'Gevp Element ${}$ - ${}$'.format(graphlabel[0], graphlabel[1])) ax.set_xlabel(r'$%s$' % graphlabel[1], fontsize=3, rotation=30) ax.set_ylabel(r'$%s$' % graphlabel[0], fontsize=3, rotation=30) # https://stackoverflow.com/questions/4209467/matplotlib-share-x-axis-but-dont-show-x-axis-tick-labels-for-both-just-one ax.label_outer() if logscale: # ax.locator_params(axis='y', numticks=3) ax.set_yscale('symlog', linthreshy=linthreshy) ax.set_xticks([]) # ax.tick_params(labelleft='off') ax.set_yticks([]) # Select data for plot graphdata = plotdata.xs(graphlabel, level=['gevp_row', 'gevp_col']) plotting_function(graphdata, ax, scale=gevp_size) if ax.legend_: ax.legend_.remove() # plt.locator_params(axis='y', numticks=2) plt.tight_layout(h_pad=0.1, w_pad=0.15) pdfplot.savefig(fig) plt.close(fig) return
return myint def str2intnew(mystr): res = '' for char in mystr: res = res + str(ord(char)) return res def str_int(s): a=0 for i in range(0,len(s)): a=a+ord(s[i])*256**i return a N = gmpy.mpz(1234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234567901234717283950617286419848309592787370341273747873748589842596504841720640394292494902982398728707626152070858561887866820294694355043665630787554216250435696249211077918492329836269203487802969283814463105539751494270071615655993342320948911726155780461076389165979343111846372150233530706650782398611627761941453287668879721303235540318234064753133821318150932201158894328482335388315649950679451828519628822971) r = int(gmpy.ceil(gmpy.sqrt(N))) p = gmpy.mpz(1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111178333333333334444487294872309872209128742098742420984723982734329843732987178261897634983473987323987439874932873402398720978429874230987340298723116269) q = gmpy.mpz(1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111178333333333334444487294872309872209128742098742420984723982734329843732987178261897634983473987323987439874932873402398720978429874230987340298723109959) e = 65537L phi = (p-1)*(q-1) d = gmpy.gcdext(e, phi)[1] if d < 0: d = d + phi val = getpass('factor 1') username = pow(gmpy.mpz(int(val[0])), e, N) username = 418296719726 password = pow(gmpy.mpz(username), d, N) print password
def sub_sub_sure_factors(f, u, curve_parameter): '''Finds all factors that can be found using ECM with a smoothness bound of u and sigma and give curve parameters. If that fails, checks for being a prime power and does Fermat factoring as well. Yields factors.''' while not (f & 1): yield 2 f >>= 1 while not (f % 3): yield 3 f /= 3 if isprime(f): yield f return log_u = math.log(u) u2 = int(_7_OVER_LOG_2 * u * log_u / math.log(log_u)) primes = [] still_a_chance = True log_mo = math.log(f + 1 + sqrt(f << 2)) g = gcd(curve_parameter, f) if g not in (1, f): for factor in sub_sub_sure_factors(g, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f/g, u, curve_parameter): yield factor return g2 = gcd(curve_parameter**2 - 5, f) if g2 not in (1, f): for factor in sub_sub_sure_factors(g2, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f / g2, u, curve_parameter): yield factor return if f in (g, g2): yield f while still_a_chance: p1 = get_points([curve_parameter], f) for prime in primes: p1 = multiply(p1, prime, f) if not isinstance(p1, list): if p1 != f: for factor in sub_sub_sure_factors(p1, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f/p1, u, curve_parameter): yield factor return else: still_a_chance = False break if not still_a_chance: break prime = 1 still_a_chance = False while prime < u2: prime = next_prime(prime) should_break = False for _ in xrange(int(log_mo / math.log(prime))): p1 = multiply(p1, prime, f) if not isinstance(p1, list): if p1 != f: for factor in sub_sub_sure_factors(p1, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(f/p1, u, curve_parameter): yield factor return else: still_a_chance = True primes.append(prime) should_break = True break if should_break: break for i in xrange(2, int(math.log(f) / LOG_2) + 2): r = root(f, i) if r[1]: for factor in sub_sub_sure_factors(r[0], u, curve_parameter): for _ in xrange(i): yield factor return a = 1 + sqrt(f) bsq = a * a - f iter = 0 while bsq != sqrt(bsq)**2 and iter < 3: a += 1 iter += 1 bsq += a + a - 1 if bsq == sqrt(bsq)**2: b = sqrt(bsq) for factor in sub_sub_sure_factors(a - b, u, curve_parameter): yield factor for factor in sub_sub_sure_factors(a + b, u, curve_parameter): yield factor return yield f return
def mainloop(n, u, p1): ''' Input: n -- an integer to (try) to factor. u -- the phase 1 smoothness bound p1 -- a list of sigma parameters to try Output: A factor of n. (1 is returned on faliure). Notes: 1. Other parameters, such as the phase 2 smoothness bound are selected by the mainloop function. 2. This function uses batch algorithms, so if p1 is not long enough, there will be a loss in efficiency. 3. Of course, if p1 is too long, then the mainloop will have to use more memory. [The memory is polynomial in the length of p1, log u, and log n].''' k = inv_const(n) log_u = math.log(u) log_log_u = math.log(log_u) log_n = math.log(n) u2 = int(_7_OVER_LOG_2 * u * log_u / log_log_u) ncurves = len(p1) w = int(math.sqrt(_3_OVER_LOG_2 * ncurves / k) - 0.5) number_of_primes = int((ncurves << w) * math.sqrt(LOG_4_OVER_9 * log_n / k) / log_u) # Lagrange multipliers! number_of_primes = min(number_of_primes, int((log_n / math.log(log_n))**2 * ncurves / log_u), int(u / log_u)) number_of_primes = max(number_of_primes, 1) m = math.log(number_of_primes) + log_log_u w = min(w, int((m - 2 * math.log(m) + LOG_3_MINUS_LOG_LOG_2) / LOG_2)) w = max(w, 1) max_order = n + sqrt(n << 2) + 1 # By Hasse's theorem. det_bound = ((1 << w) - 1 + ((w & 1) << 1)) / 3 log_mo = math.log(max_order) p = range(number_of_primes) prime = mpz(2) p1 = get_points(p1, n) if not isinstance(p1, list): return p1 for _ in xrange(int(log_mo / LOG_2)): p1 = double(p1, n) if not isinstance(p1, list): return p1 for i in xrange(1, det_bound): prime = (i << 1) + 1 if isprime(prime): for _ in xrange(int(log_mo / math.log(prime))): p1 = multiply(p1, prime, n) if not isinstance(p1, list): return p1 while prime < sqrt(u) and isinstance(p1, list): for i in xrange(number_of_primes): prime = next_prime(prime) p[i] = prime ** max(1, int(log_u / math.log(prime))) p1 = fast_multiply(p1, prod(p), n, w) if not isinstance(p1, list): return p1 while prime < u and isinstance(p1, list): for i in xrange(number_of_primes): prime = next_prime(prime) p[i] = prime p1 = fast_multiply(p1, prod(p), n, w) if not isinstance(p1, list): return p1 del p small_jump = int(greatest_n((1 << (w + 2)) / 3)) small_jump = max(120, small_jump) big_jump = 1 + (int(sqrt((5 << w) / 21)) << 1) total_jump = small_jump * big_jump big_multiple = max(total_jump << 1, ((int(next_prime(prime)) - (total_jump >> 1)) / total_jump) * total_jump) big_jump_2 = big_jump >> 1 small_jump_2 = small_jump >> 1 product = ONE psmall_jump = multiply(p1, small_jump, n) if not isinstance(psmall_jump, list): return psmall_jump ptotal_jump = multiply(psmall_jump, big_jump, n) if not isinstance(ptotal_jump, list): return ptotal_jump pgiant_step = multiply(p1, big_multiple, n) if not isinstance(pgiant_step, list): return pgiant_step small_multiples = [None] for i in xrange(1, small_jump >> 1): if gcd(i, small_jump) == 1: tmp = multiply(p1, i, n) if not isinstance(tmp, list): return tmp for i in xrange(len(tmp)): tmp[i] = tmp[i][0] small_multiples.append(tuple(tmp)) else: small_multiples.append(None) small_multiples = tuple(small_multiples) big_multiples = [None] for i in xrange(1, (big_jump + 1) >> 1): tmp = multiply(psmall_jump, i, n) if not isinstance(tmp, list): return tmp big_multiples.append(to_tuple(tmp)) big_multiples = tuple(big_multiples) psmall_jump = to_tuple(psmall_jump) ptotal_jump = to_tuple(ptotal_jump) while big_multiple < u2: big_multiple += total_jump center_up = big_multiple center_down = big_multiple pgiant_step = add(ptotal_jump, pgiant_step, n) if not isinstance(pgiant_step, list): return pgiant_step prime_up = next_prime(big_multiple - small_jump_2) while prime_up < big_multiple + small_jump_2: s = small_multiples[abs(int(prime_up) - big_multiple)] for j in xrange(ncurves): product *= pgiant_step[j][0] - s[j] product %= n prime_up = next_prime(prime_up) for i in xrange(1, big_jump_2 + 1): center_up += small_jump center_down -= small_jump pmed_step_up, pmed_step_down = add_sub_x_only(big_multiples[i], pgiant_step, n) if pmed_step_down == None: return pmed_step_up while prime_up < center_up + small_jump_2: s = small_multiples[abs(int(prime_up) - center_up)] for j in xrange(ncurves): product *= pmed_step_up[j] - s[j] product %= n prime_up = next_prime(prime_up) prime_down = next_prime(center_down - small_jump_2) while prime_down < center_down + small_jump_2: s = small_multiples[abs(int(prime_down) - center_down)] for j in xrange(ncurves): product *= pmed_step_down[j] - s[j] product %= n prime_down = next_prime(prime_down) if gcd(product, n) != 1: return gcd(product, n) return 1
a = 1 yield a b = 5 yield b r = 0 while r < n: r = 6 * b - a yield r a = b b = r nums = seq_A001653() tr = next(nums) while True: tr = next(nums) s = tr ** 2 if (not gmpy.is_square(2 * s - 1)): continue t = (1 + gmpy.sqrt(2 * s - 1)) / 2 r = 1 + 2 * t ** 2 - 2 * t if (gmpy.is_square(r)): if (r % 2 == 1): print int(1+gmpy.sqrt(r))/2, t if (t > 10 ** 12): break