def computeN3Factors(): A = gmpy2.ceil(gmpy2.mul(2, gmpy2.sqrt(gmpy2.mul(6, N3)))) X = gmpy2.ceil( gmpy2.sqrt( gmpy2.sub( pow(A, 2), gmpy2.mul(24, N3) ) ) ) p = gmpy2.ceil(gmpy2.div(gmpy2.sub(A, X), 6)) # Only round one. q = gmpy2.div(N3, p) confirmed(N3, p, q)
def calc_brute_force(self): a = ceil(sqrt(self.n)) for n in xrange(1, 2 ** 20): p, q = self._calc_factors(add(a, n)) if self._check_sol(p, q): return p, q #self.log.print_progress(n) else: raise ValueError("Cannot factor {}".format(self.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 main(): # predefine these, we will stop overwriting them when ready to run the big numbers p=mpz('13407807929942597099574024998205846127' '47936582059239337772356144372176403007' '35469768018742981669034276900318581848' '6050853753882811946569946433649006084171' ) g=mpz('117178298803662070095161175963353670885' '580849999989522055999794590639294997365' '837466705721764714603129285948296754282' '79466566527115212748467589894601965568' ) y=mpz('323947510405045044356526437872806578864' '909752095244952783479245297198197614329' '255807385693795855318053287892800149470' '6097394108577585732452307673444020333' ) log.info("Starting Discrete Log Calculation") log.info("p: %i", p) log.info("g: %i", g) log.info("y: %i", y) m = gmpy2.ceil(gmpy2.sqrt(p)) log.info("m: %i", m) # custom range since builtin has a size limit long_range = lambda start, stop: iter(itertools.count(start).next, stop) chunk_size = 100000 if m < 100000: chunk_size = m stop_at = chunk_size start = 0 while True: chunk = {} log.info("Starting chunk from %i to %i", start, stop_at) for i in xrange(start, stop_at): chunk[gmpy2.powmod(g,i,p)] = i for t in long_range(0,m): expone = mpz(gmpy2.mul(-m,t)) g_term = gmpy2.powmod(g, expone, p) res = gmpy2.f_mod(gmpy2.mul(y, g_term), p) if res in chunk: s = chunk[res] dc = gmpy2.f_mod(mpz(gmpy2.add(s, gmpy2.mul(m,t))), p) log.info("DC LOG FOUND") log.info("dc: %i", dc) return log.info("Completed chunk run: %i to %i no DC yet :(", start, stop_at) start = stop_at stop_at += chunk_size
def fermat_factor(n): assert n % 2 != 0 # Odd integers only a = gmpy2.ceil(gmpy2.sqrt(n)) b2 = gmpy2.square(a) - n while not is_square(b2): a += 1 b2 = gmpy2.square(a) - n factor1 = a + gmpy2.sqrt(b2) factor2 = a - gmpy2.sqrt(b2) return int(factor1), int(factor2)
def factor3(n): a = ceil(sqrt(6 * n)) - 0.5 x_square = a**2 - 6 * n x = sqrt(x_square) if (a - x) % 3 == 0: # 3p<2q => p<q return mpz((a - x) / 3) elif (a - x) % 2 == 0: # 2q<3p q = (a - x) / 2 if q < n / q: return mpz(q) else: return mpz(n / q)
def encode(self, seq): assert len(seq) == len(self.SNPRefList) L = [-1, -1] U = [-1, -1] L[0] = mpz(0) U[0] = mpz(self.maxSeed) n = len(seq) for i in range(1, n + 1): probs = self.condProb(seq[:i]) sortInd = np.argsort(probs) assignedRangeSize = [0] * 3 available = U[(i - 1) % 2] - L[(i - 1) % 2] + 1 if probs[sortInd[0]] * available < self.powOfThree[n - i]: assignedRangeSize[sortInd[0]] = self.powOfThree[n - i] else: assignedRangeSize[sortInd[0]] = mpz( gmpy2.ceil(probs[sortInd[0]] * available)) available -= assignedRangeSize[sortInd[0]] probs[sortInd[0]] = 0 probs = probs / sum( probs) #re-normalize the remaining two probabilities if probs[sortInd[1]] * available < self.powOfThree[n - i]: assignedRangeSize[sortInd[1]] = self.powOfThree[n - i] else: assignedRangeSize[sortInd[1]] = mpz( gmpy2.ceil(probs[sortInd[1]] * available)) assignedRangeSize[ sortInd[2]] = available - assignedRangeSize[sortInd[1]] L[i % 2] = L[(i - 1) % 2] + sum(assignedRangeSize[:seq[i - 1]]) U[i % 2] = L[(i - 1) % 2] + sum( assignedRangeSize[:(seq[i - 1] + 1)]) - 1 #Don't use random.randint for big integer. Sometimes they might be correct on a system, but sometimes they are not. #I encounter this problem when running this script with condor on icsil1-cluster.epfl.ch. The function generates very strange and unexpected integers. #seed = random.randint(L[n%2], U[n%2]) tmp = random.randint(0, 2**30) randomState = gmpy2.random_state(tmp) seed = gmpy2.mpz_random(randomState, U[n % 2] - L[n % 2] + 1) + L[n % 2] return seed
def decode(self, seed): L = [-1, -1] U = [-1, -1] L[0] = mpz(0) U[0] = mpz(self.maxSeed) n = len(self.SNPRefList) seq = [-1] * n for i in range(1, n + 1): probs = self.condProb(seq[:i]) sortInd = np.argsort(probs) assignedRangeSize = [0] * 3 available = U[(i - 1) % 2] - L[(i - 1) % 2] + 1 if probs[sortInd[0]] * available < self.powOfThree[n - i]: assignedRangeSize[sortInd[0]] = self.powOfThree[n - i] else: assignedRangeSize[sortInd[0]] = mpz( gmpy2.ceil(probs[sortInd[0]] * available)) available -= assignedRangeSize[sortInd[0]] probs[sortInd[0]] = 0 probs = probs / sum( probs) #re-normalize the remaining two probabilities if probs[sortInd[1]] * available < self.powOfThree[n - i]: assignedRangeSize[sortInd[1]] = self.powOfThree[n - i] else: assignedRangeSize[sortInd[1]] = mpz( gmpy2.ceil(probs[sortInd[1]] * available)) assignedRangeSize[ sortInd[2]] = available - assignedRangeSize[sortInd[1]] if seed < L[(i - 1) % 2] + sum(assignedRangeSize[:1]): seq[i - 1] = 0 elif seed < L[(i - 1) % 2] + sum(assignedRangeSize[:2]): seq[i - 1] = 1 elif seed < L[(i - 1) % 2] + sum(assignedRangeSize[:3]): seq[i - 1] = 2 else: raise ValueError("Invalid Seed") L[i % 2] = L[(i - 1) % 2] + sum(assignedRangeSize[:seq[i - 1]]) U[i % 2] = L[(i - 1) % 2] + sum( assignedRangeSize[:(seq[i - 1] + 1)]) - 1 return seq
def challenge3(): """ Valid when |3p - 2q| < N^(1/4) Solving >>> 6N = A^2 - i^2 - A + i >>> [ax^2 + bx + c = 0] >>> 1i^2 - 1i - (A^2 - A - 6N) = 0 Therefore: a = 1 b = -1 c = (A^2 - A - 6N) """ print("> Challenge 3") N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 A = gmpy2.ceil(gmpy2.sqrt(6*N)) a = gmpy2.mpz(1) b = gmpy2.mpz(-1) c = gmpy2.mpz(-(A**2 - A - 6*N)) # Solving using quadratic formula # # x = (-b (+/-) b^2 - 4ac) / 2a # # b^2 - 4ac det = gmpy2.isqrt(b**2 - 4*a*c) plus = gmpy2.div(-b + det, 2*a) minus = gmpy2.div(-b - det, 2*a) answers = [plus, minus] for i in answers: # check for correct answer p = gmpy2.mpz(gmpy2.div(A + i - 1, 3)) q = gmpy2.mpz(gmpy2.div(A - i, 2)) # values found if p*q == N: printSmallest(p, q) return raise(Exception("[Challenge 3] > Could not find p or q"))
def is_good_pair(p: int, q: int) -> Optional[Tuple[int, int]]: """Returns the encryption modulus and totient for the given primes. :param p: One of the two primes to be used for encryption. :type p: int :param q: The other prime used for encryption. :type q: int :returns: Either the encryption modulus and the totient, or None. :rtype: Optional[Tuple[int, int]]""" n = p*q k = gmpy2.ceil(gmpy2.log2(n)) if abs(p - q) > 2**(k/2 - 100): return n, n - (p + q - 1) return None
def q1(): N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 rt = gmpy2.sqrt(N) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def q3(): N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 rt = gmpy2.sqrt(gmpy2.mul(N, 6)) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) x = gmpy2.mul(x, 3 / 2) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def question2(): #25464796146996183438008816563973942229341454268524157846328581927885777969985222835143851073249573454107384461557193173304497244814071505790566593206419759 N = gmpy2.mpfr( "648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 1050) A = gmpy2.ceil((gmpy2.sqrt(N))) #print("A:",A) i = 1 while i < 2**20: #print("K:",k) x = gmpy2.ceil(gmpy2.sqrt(gmpy2.square(A) - N)) #print("x:",x) p = A + x q = A - x if (N == gmpy2.mul(p, q)): if (p > q): p, q = q, p print("found pq:", p, q) break A += 1 i += 1
def FermatFactor(N): A = gmpy2.mpz( gmpy2.ceil( gmpy2.sqrt(N) ) ) B2 = gmpy2.sub( gmpy2.square(A), N ) while not gmpy2.is_square(B2): A = gmpy2.add( A, gmpy2.mpz("1") ) B2 = gmpy2.sub( gmpy2.square(A), N ) B = gmpy2.sqrt(B2) P = gmpy2.mpz( gmpy2.sub( A, B ) ) Q = gmpy2.mpz( gmpy2.add( A, B ) ) if not checkFactors(P,Q,N): raise Exception("Bad factors generated") return ( P, Q )
def q3(): N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 rt = gmpy2.sqrt(gmpy2.mul(N, 6)) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) x = gmpy2.mul(x, 3/2) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def ex3(): N = mpz( 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 ) sqrt_6N = sqrt(6 * N) sqrt_6N_decimal = sqrt_6N % 1 if sqrt_6N_decimal < 0.5: A = floor(sqrt_6N) + 0.5 else: A = ceil(sqrt_6N) x = sqrt(A**2 - 6 * N) # P = 3 * p # Q = 2 * q P = A - x p = mpz(P / 3) print(p)
def challenge1(): print("> Challenge 1") N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 N_sqrt = gmpy2.sqrt(N) # A = round(√N) A = gmpy2.ceil(N_sqrt) # x = √(A^2 - N) x = gmpy2.sqrt(pow(A, 2) - N) p = A - x q = A + x printSmallest(p, q) return p, q, N
def q2(): N = 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 rt = gmpy2.sqrt(N) A = gmpy2.ceil(rt) q = 0 p = 0 while not gotcha(N, p, q): A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) assert N == gmpy2.mul(p, q) A += 1
def challenge2(): """ Uses Fermant factorisation """ print("> Challenge 2") N = 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 N_sqrt = gmpy2.sqrt(N) A = gmpy2.ceil(N_sqrt) b2 = A * A - N while not gmpy2.is_square(gmpy2.mpz(b2)): A = A + 1 b2 = A * A - N # Works out p and q q = A - gmpy2.sqrt(b2) p = N / q printSmallest(p, q)
def findFactorsCaseOne(self): print("===========================================") print("Modulus N is: " + str(self.N)) #A = (p+q)/2 == ceil(sqrt(N)) A = gmpy2.ceil(gmpy2.sqrt(self.N)) print("A is: " + str(A)) #x = sqrt(A^2 - N) A_square = gmpy2.mul(A, A) x = gmpy2.sqrt(gmpy2.sub(A_square, self.N)) print("x is: " + str(x)) #p = A - x AND q = A + x self.p = gmpy2.sub(A, x) self.q = gmpy2.add(A, x) prod = gmpy2.mul(self.p, self.q) print("Product of pq is: " + str(prod)) if prod == self.N: print("We have got the factors RIGHT") else: print("We didn't get the factors") print(self.p) print(self.q) self.p = 0 self.q = 0 print("===========================================")
def findFactorsCaseThree(self): print("===========================================") print("Modulus N is: " + str(self.N)) #A = ceil(2 * sqrt(6N)) A = gmpy2.ceil(gmpy2.mul(mpz(2), gmpy2.sqrt(gmpy2.mul(mpz(6), self.N)))) print("A is: " + str(A)) #X = sqrt(A^2 - 24N) A_square = gmpy2.mul(A, A) X = gmpy2.sqrt(gmpy2.sub(A_square, gmpy2.mul(mpz(24), self.N))) print("X is: " + str(X)) #q = (A + X)/4 AND p = N/q self.q = gmpy2.f_div(mpz(gmpy2.add(A, X)), mpz(4)) self.p = gmpy2.div(self.N, self.q) prod = gmpy2.mul(self.p, self.q) print("Product of pq is: " + str(prod)) if prod == self.N: print("We have got the factors RIGHT") else: print("We didn't get the factors") print(self.p) print(self.q) self.p = 0 self.q = 0 print("===========================================")
def factor(N): # type: (int) -> int """ Computes a factorization of N using pure Fermat approach Expects N to be odd (i.e. 3, 5, etc.) and throws a ValueError otherwise. See: https://en.wikipedia.org/wiki/Fermat%27s_factorization_method Args: N: the number to factorize Returns: A factor of N """ if N & 1 == 0: return gmpy2.mpz(2) if gmpy2.get_context().precision < PRECISION_BITS: adjust_gmpy2_precision(PRECISION_BITS) logger = logging.getLogger(LOGGER) a = gmpy2.mpz(gmpy2.ceil(gmpy2.sqrt(N))) b = a * a - N while not gmpy2.is_square(b): a = a + 1 b = a * a - N logger.info("Iteration {} and {}".format(a, b)) # NOTE: must convert to integer before subtraction result = a - gmpy2.mpz(gmpy2.sqrt(b)) return result
def findFactorsCaseTwo(self): print("===========================================") print("Modulus N is: " + str(self.N)) #A = (p+q)/2 AND A can be any where from ceil(sqrt(N)) to ceil(sqrt(N)) + 2 ^ 20 A = gmpy2.ceil(gmpy2.sqrt(self.N)) print("A is: " + str(A)) upperRange = 2 ** 20 for index in range (0, upperRange + 1): #x = sqrt(A^2 - N) A_square = gmpy2.mul(A, A) diff = gmpy2.sub(A_square, self.N) x = mpz(gmpy2.sqrt(diff)) #p = A - x AND q = A + x self.p = gmpy2.sub(A, x) self.q = gmpy2.add(A, x) prod = gmpy2.mul(self.p, self.q) if prod == self.N: print("We have got the factors RIGHT") return else: A = A + 1 print("We didn't get the factors") self.p = 0 self.q = 0
N1 += '0071584560878577663743040086340742855278549092581' N2 = '6484558428080716696628242653467722787263437207069762630604390703787' N2 += '9730861808111646271401527606141756919558732184025452065542490671989' N2 += '2428844841839353281972988531310511738648965962582821502504990264452' N2 += '1008852816733037111422964210278402893076574586452336833570778346897' N2 += '15838646088239640236866252211790085787877' N3 = '72006226374735042527956443552558373833808445147399984182665305798191' N3 += '63556901883377904234086641876639384851752649940178970835240791356868' N3 += '77441155132015188279331812309091996246361896836573643119174094961348' N3 += '52463970788523879939683923036467667022162701835329944324119217381272' N3 += '9276147530748597302192751375739387929' diff = 1 gmpy2.set_context(gmpy2.context(precision = 3000)) N = mpz(N3) lowerBound = mpz(gmpy2.ceil(gmpy2.mul(2, gmpy2.sqrt(gmpy2.mul(6, N))))) for i in range(0, diff): A = gmpy2.div(mpfr(gmpy2.add(lowerBound, i)), 2) SquareA = gmpy2.square(A) x = gmpy2.sqrt(gmpy2.sub(SquareA, gmpy2.mul(6, N))) if gmpy2.is_integer(gmpy2.div(gmpy2.sub(A, x), 3)) and gmpy2.is_integer(gmpy2.div(gmpy2.add(A, x), 2)): print 'p = ' + str(mpz(gmpy2.div(gmpy2.sub(A, x), 3))) print 'q = ' + str(mpz(gmpy2.div(gmpy2.add(A, x), 2))) else: print 'p = ' + str(mpz(gmpy2.div(gmpy2.add(A, x), 3))) print 'q = ' + str(mpz(gmpy2.div(gmpy2.sub(A, x), 2)))
# brew install gmp # brew install mpfr # brew install libmpc # bin/easy_install http://gmpy.googlecode.com/files/gmpy2-2.0.0b1.zip # wget http://www.math.umbc.edu/~campbell/Computers/Python/numbthy.py from __future__ import division # division with floats import gmpy2 gmpy2.get_context().precision = 1100 N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 A = gmpy2.ceil(gmpy2.sqrt(N)) A2 = A**2 print "N :", int(N) print "sq(A): %.f" % gmpy2.sqrt(N) print "round:", int(gmpy2.ceil(gmpy2.sqrt(N))) print "A^2 :", int(A2) assert A2 > N x = gmpy2.sqrt(A2 - N) print "x :", int(x) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) print "p*q :", int(gmpy2.mul(p, q))
def part1(): A = gmpy2.ceil(gmpy2.sqrt(N)) x = gmpy2.mpz(gmpy2.ceil(gmpy2.sqrt(A**2 - N))) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) return p
q = A - x return q if p * q == N else -1 def int_to_bytes(value, length): ## Function to be used in Q4. result = [] for i in range(0, length): result.append(value >> (i * 8) & 0xff) result.reverse() return bytes(result) # Q1 (Given : |p - q| < 2*N^0.25) N1 = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 A1 = int(gmpy2.ceil(gmpy2.sqrt(N1))) print("Ans 1. : %d" % factor(A1, N1)) # Q2 (Given : |p - q| < 2^11 * N^0.25) N2 = 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 A2 = int(gmpy2.ceil(gmpy2.sqrt(N2))) for i in range(2**20): q = factor(A2 + i, N2) if q != -1: print("Ans 2. : %d" % q) break # Q3 (Given : |3p - 2q| < N^0.25) N3 = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929
N1 = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 # Tests print("test") print(169.0 % 1) print(38.509658609 % 1) # Challenge 1 gmpy2.get_context().precision = 1030 temp = gmpy2.sqrt(N1) # print("t = ", temp) A = gmpy2.ceil(temp) print("A = ", A) temp2 = A * A temp3 = temp2 - N1 x = gmpy2.sqrt(temp3) p = A - x p4 = p print("p= ", p) q = A + x q4 = q print("q= ", q)
def factor1(n): a = mpz(ceil(sqrt(n))) x = sqrt(a**2 - n) return mpz(a - x)
import gmpy2 from gmpy2 import mpz from gmpy2 import mpfr gmpy2.get_context().precision = 2000 N1 = mpz("179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581") A1 = gmpy2.isqrt(N1) + 1 #A = (p+q/2) and is close to sqrt(N), so sqrt(N) is used to estimate A x1 = gmpy2.isqrt(A1**2 - N1) p1 = A1 - x1 q1 = A1 + x1 print p1 N2 = mpz("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877") A2 = gmpy2.isqrt(N2) + 1 while not gmpy2.is_square(A2**2 - N2): A2 = A2 + 1 print A2 - gmpy2.isqrt(A2**2 - N2) N3 = mpz("720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929") A3 = gmpy2.ceil(gmpy2.sqrt(6*N3)*2)/2 print (A3 - gmpy2.sqrt(A3**2 - 6*N3))/3 e_m = mpz("22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540") phi = (p1 - 1)*(q1 - 1) d = gmpy2.invert(65537, phi) d_m = gmpy2.powmod(e_m, d, N1) hex = d_m.digits(16) hex = hex[hex.find("00")+2:] print hex.decode("hex")
def fac3(N): root6N = 2 * gmpy2.sqrt(6 * N) Ax2 = gmpy2.ceil(root6N) A = Ax2 / 2 x = gmpy2.sqrt(A**2 - 6 * N) p = (A - x) / 3 q = (A + x) / 2 print('p:\n' + str(int(p))) print('q:\n' + str(int(q))) return (int(p), int(q)) rootN = gmpy2.sqrt(N) #print('rootN:', rootN) #A = gmpy2.ceil(gmpy2.sqrt(N)) A = gmpy2.ceil(rootN) rootNsq = rootN**2 Ncalc = N - rootNsq #print('A:', A, 'A>N:', A>N, 'A>rootN:', A>rootN, 'Ncalc:', Ncalc) # Since A is the exact mid-point between p and q there is an integer x # such that p=A−x and q=A+x. # But then N=pq=(A−x)(A+x)=A2−x2 and therefore x=A2−N**.5 res1 = gmpy2.mpz(A**2 - N) #print('res1:', res1) x = gmpy2.sqrt(A**2 - N) #print('x:', x) # Now, given x and A you can find the factors p and q of N since p=A−x and q=A+x.
def good_pair(p: int, q: int) -> int: n = p * q k = gmpy2.ceil(gmpy2.log2(n)) if abs(p - q) > 2**(k / 2 - 100): return n return 0
def is_prime_by_AKS(n): """ 使用AKS算法确定n是否是一个素数 True:n是素数 False:n是合数 """ def __is_integer__(n): """ 判断一个数是否是整数 """ i = gmpy2.mpz(n) f = n - i return not f def __phi__(n): """ 欧拉函数,测试小于n并与n互素的个数 """ res = gmpy2.mpz(n) a = gmpy2.mpz(n) for i in range(2, a + 1): if a % i == 0: res = res // i * (i - 1) while a % i == 0: a //= i if a > 1: res = res // a * (a - 1) return res def __gcd__(a, b): """ 计算a b的最大公约数 """ if b == 0: return a return __gcd__(gmpy2.mpz(b), gmpy2.mpz(a) % gmpy2.mpz(b)) print("步骤1, 确定%d是否是纯次幂" % n) for b in range(2, gmpy2.mpz(gmpy2.floor(gmpy2.log2(n))) + 1): a = n**(1 / b) if __is_integer__(a): return False print("步骤2,找到一个最小的r,符合o_r(%d) > (log%d)^2" % (n, n)) maxk = gmpy2.mpz(gmpy2.floor(gmpy2.log2(n)**2)) maxr = max(3, gmpy2.mpz(gmpy2.ceil(gmpy2.log2(n)**5))) nextR = True r = 0 for r in range(2, maxr): if nextR == False: break nextR = False for k in range(1, maxk + 1): if nextR == True: break nextR = (gmpy2.mpz(n**k % r) == 0) or (gmpy2.mpz(n**k % r) == 1) r = r - 1 # 循环多增加了一层 print("r = %d" % r) print("步骤3,如果 1 < gcd(a, %d) < %d,对于一些 a <= %d, 输出合数" % (n, n, r)) for a in range(r, 1, -1): g = __gcd__(a, n) if g > 1 and g < n: return False print("步骤4,如果n=%d <= r=%d,输出素数" % (n, r)) if n <= r: return True print("步骤5") print("遍历a从1到\sqrt{\phi(r=%d)}logn=%d" % (r, n)) print("如果(X+a)^%d != X^%d+a mod {X^%d-1, %d}$输出合数" % (n, n, r, n)) # 构造P = (X+a)^n mod (X^r-1) print("构造多项式(X+a)^%d,并且进行二项式展开" % n) X = multi_ysymbols('X') a = multi_ysymbols('a') X_a_n_expand = binomial_expand(ypolynomial1(X, a), n) print(X_a_n_expand) X.pow(r) reduce_poly = ypolynomial1(X, ysymbol(value=-1.0)) print("构造消减多项式 %s" % reduce_poly) print("进行运算 (X+a)^%d mod (X^%d-1)" % (n, r)) r_equ = ypolynomial_mod(X_a_n_expand, reduce_poly) print("得到余式: %s" % r_equ) print("进行运算'余式' mod %d 得到式(A)" % n) A = ypolynomial_reduce(r_equ, n) print("A = %s" % A) print("B = x^%d+a mod x^%d-1" % (n, r)) B = ypolynomial1(multi_ysymbols('X', power=31), a) B = ypolynomial_mod(B, reduce_poly) print("B = %s" % B) C = ypolynomial_sub(A, B) print("C = A - B = %s" % C) maxa = math.floor(math.sqrt(__phi__(r)) * math.log2(n)) print("遍历a = 1 to %d" % maxa) print("检查每个'%s = 0 (mod %d)'" % (C, n)) for a in range(1, maxa + 1): print("检查a = %d" % a) C.set_variables_value(a=a) v = C.eval() if v % n != 0: return False print("步骤6 输出素数") return True
import gmpy2 from gmpy2 import mpz __author__ = 'Qubo' N1 = '17976931348623159077293051907890247336179769789423065727343008115' N1 += '77326758055056206869853794492129829595855013875371640157101398586' N1 += '47833778606925583497541085196591615128057575940752635007475935288' N1 += '71082364994994077189561705436114947486504671101510156394068052754' N1 += '0071584560878577663743040086340742855278549092581' gmpy2.set_context(gmpy2.context(precision=2000)) N = mpz(N1) A = gmpy2.ceil(gmpy2.sqrt(N)) SquareA = gmpy2.square(A) if gmpy2.is_square(mpz(gmpy2.sub(SquareA, N))): x = gmpy2.sqrt(gmpy2.sub(SquareA, N)) print 'p = ' + str(mpz(gmpy2.sub(A, x))) print 'q = ' + str(mpz(gmpy2.add(A, x))) else: print 'x is not square, must be wrong...'
def random_from_interval(random_state, low, high, m=32): M = int(g.ceil(g.log2(high))) random = g.mpz_urandomb(random_state, M + m) c = g.add(g.f_mod(random, g.add(g.sub(high, low), 1)), low) return c
def calc_near(self): a = ceil(sqrt(self.n)) p, q = self._calc_factors(a) assert self._check_sol(p, q) assert gmpy2.is_prime(p) return p, q
from gmpy2 import mpz __author__ = 'Qubo' N1 = '17976931348623159077293051907890247336179769789423065727343008115' N1 += '77326758055056206869853794492129829595855013875371640157101398586' N1 += '47833778606925583497541085196591615128057575940752635007475935288' N1 += '71082364994994077189561705436114947486504671101510156394068052754' N1 += '0071584560878577663743040086340742855278549092581' N2 = '6484558428080716696628242653467722787263437207069762630604390703787' N2 += '9730861808111646271401527606141756919558732184025452065542490671989' N2 += '2428844841839353281972988531310511738648965962582821502504990264452' N2 += '1008852816733037111422964210278402893076574586452336833570778346897' N2 += '15838646088239640236866252211790085787877' diff = 2 ** 20 gmpy2.set_context(gmpy2.context(precision = 3000)) N = mpz(N2) lowerBound = mpz(gmpy2.ceil(gmpy2.sqrt(N))) for i in range(0, diff): A = gmpy2.add(lowerBound, i) SquareA = gmpy2.square(A) if gmpy2.is_square(gmpy2.sub(SquareA, N)): x = mpz(gmpy2.sqrt(gmpy2.sub(SquareA, N))) print 'p = ' + str(gmpy2.sub(A, x)) print 'q = ' + str(gmpy2.add(A, x))
def factor(A, N): # Assuming A = (p + q)/2 ## Function to be used in Q1,Q2. A_square = int(gmpy2.ceil(gmpy2.square(A))) x = int(gmpy2.ceil(gmpy2.sqrt(A_square - N))) p = A + x q = A - x return q if p * q == N else -1
tmp_2 = gmpy2.powmod(tmp_1, i, p) tmp_3 = gmpy2.powmod(gmpy2.mul(b, tmp_2), 1, p) giant_x.append(tmp_3) return giant_x def get_result(baby_x, giant_x, m): for x_b in baby_x: for x_g in giant_x: if x_b == x_g: return gmpy2.add(gmpy2.mul(giant_x.index(x_g), m), baby_x.index(x_b)) if __name__ == '__main__': p = int(input('输入p:')) a = int(input('输入α:')) b = int(input('输入β:')) ord = get_ord(p) print('ord:' + str(ord)) m = int(gmpy2.ceil(gmpy2.sqrt(ord))) print('m=' + str(m)) baby_x = get_baby_x(a, p, m) print('x_b:' + str(baby_x)) giant_x = get_giant_x(a, b, m, p) print('x_g:' + str(giant_x)) result = get_result(baby_x, giant_x, m) print(result)
def computeA(N): return gmpy2.ceil(gmpy2.sqrt(N))
def max_bits_in_digits(d): """ Returns maximum number of bits fitting in given number of digits eg. 2 digits (99) fits in 7 bits :param d: number of digits """ return gmpy2.mpz(gmpy2.ceil(d * (gmpy2.log(10) / gmpy2.log(2))))
import numpy import gmpy2 import math from collections import defaultdict from gmpy2 import mpz gmpy2.get_context().precision=10000 N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 N=179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 N=648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 N=720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 N= mpz(N)*6 A=gmpy2.ceil(gmpy2.sqrt(gmpy2.mpz(N))) B=numpy.powmod(2,20,N) for i in range(0,B+1): print i #x=mpz(A*A) -N A=mpz(A) z=mpz(A)*mpz(A) #print mpz(z)+1 y=mpz(z)-mpz(N) x=gmpy2.sqrt(gmpy2.mpz(y)) p=mpz(A)-mpz(x) q=mpz(A)+mpz(x) #print p #print mpz(p)
gmpy2.get_context().precision=500*8 n50b = "543971971236630195076898180273" n60b = "459344432904829185748347139878533089" n70b = "810814527278919159798277223576982175301717" n80b = "662875573009490731045345994740327457245824480677" n25b = 767971435180333 test = 90283 N = gmpy2.mpz(n70b) n_smooth = 1500 offset = 800000000 start = 0 listN = [] start = gmpy2.mpz(gmpy2.ceil(gmpy2.sqrt(N))) def init(): for j in range(0, offset): listN.append(gmpy2.sub(gmpy2.mul(gmpy2.add(start, j), gmpy2.add(start, j)), N)) return start def read_prime(): list_primes = [] with open("primes1000.txt") as fp: for line in fp: list_primes.extend([int(s) for s in re.split(r'\s+', line.strip())]) print("list prime:") print(list_primes) return list_primes