def greatest_n(phi_max): '''Finds the greatest n such that phi(n) < phi_max. Returns the greatest n such that phi(n) < phi_max.''' phi_product = 1 product = 1 prime = 1 while phi_product <= phi_max: prime = next_prime(prime) phi_product *= prime - 1 product *= prime n_max = (phi_max * product) / phi_product phi_values = range(n_max) prime = 2 while prime <= n_max: for i in xrange(0, n_max, prime): phi_values[i] -= phi_values[i] / prime prime = next_prime(prime) for i in xrange(n_max - 1, 0, -1): if phi_values[i] <= phi_max: return i
def factor_bounded_pm1(n, b, degree='auto'): print 'start' a = 2 i = 0 q = 2 if degree == 'auto': while q < b: i += 1 if i % 1000 == 0: print 'Progress:', q, b base = q**int(math.floor(1 / math.log(q, n))) a = pow(a, base, n) g = gmpy.gcd(a - 1, n) if g != 1 and g != n: return int(g) q = gmpy.next_prime(q) return None else: while q < b: i += 1 if i % 1000 == 0: print 'Progress:', q, b base = q**degree a = pow(a, base, n) g = gmpy.gcd(a - 1, n) if g != 1 and g != n: return int(g) q = gmpy.next_prime(q) return None
def main(): year = 3 bits = 512 boggart_fear = 31337 boggart_danger = 16 neutral_magic, light_magic, dark_magic = [ getrandbits(bits) for _ in range(3) ] magic = next_prime(neutral_magic | light_magic) * next_prime(neutral_magic | dark_magic) print( 'Hello. I am Professor Remus Lupin. Today I\'m going to show you how to deal with the boggart.' ) print(neutral_magic) print(magic) with open('flag.txt', 'rb') as file: flag = file.read().strip() # some young wizards without knowledge of the riddikulus charm harry_potter = Wizard(magic, year, bytes_to_long(b'the boy who lived')) you = Wizard(magic, year, bytes_to_long(flag)) for boggart in Wardrobe.create_boggarts(boggart_fear, boggart_danger): # wizards should train to learn the riddikulus charm harry_potter.cast_riddikulus(boggart) you.cast_riddikulus(boggart) # wizard's experience should be increased print(harry_potter.experience) print(you.experience)
def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1) * (q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2 * p * q) e = gmpy.next_prime(e**2)
def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2)
def _find_safe_prime(bits, randfunc=None): """ Finds a safe prime of `bits` bits """ r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc)) q = gmpy.next_prime(r) p = 2*q+1 if gmpy.is_prime(p): return p
def factorize(x=c): r''' (Takes about 25ms, on c, on a first-generation Macbook Pro) >>> factorize(a) [3, 41] >>> factorize(b) [2, 2, 2, 3, 19] >>> ''' import gmpy as _g savex = x prime = 2 x = _g.mpz(x) factors = [] while x >= prime: newx, mult = x.remove(prime) if mult: factors.extend([int(prime)] * mult) x = newx prime = _g.next_prime(prime) for factor in factors: assert _g.is_prime(factor) from operator import mul assert reduce(mul, factors) == savex return factors
def sq(q): assert is_prime(q) p = 2 while True: if p != q: yield p * p * q * q * q p = int(next_prime(p))
def exploit(mp) : p = mp - 9000000 while True : q = n//p if p*q == n : return p,q p = next_prime(p)
def sq(q): assert is_prime(q) p = 2 while True: if p != q: yield p*p*q*q*q p = int(next_prime(p))
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 prev_prime(p): lo = find_low(p) pp = next_prime(lo) hi = p while lo < hi: mid = (lo + hi) // 2 print mid mid_p = next_prime(mid) if (mid_p == p): hi = mid else: pp = mid_p lo = mid + 1 return pp
def main(): rsa1 = RSA(3, getPrime(2048), getPrime(2048)) p = getPrime(2048) rsa2 = RSA(65537, p, next_prime(p)) rsa3 = RSA(65537, getPrime(128), getPrime(128)) random.seed(os.urandom(8)) list_rsa = [rsa1, rsa2, rsa3] random.shuffle(list_rsa) print(""" Complete the following three questions """) try: for i in range(3): m = int(os.urandom(16).encode("hex"), 16) print("e :" + list_rsa[i].getExponent()) print("N :" + list_rsa[i].getModulus()) print("c :" + list_rsa[i].encrypt(m)) ans = raw_input("m >> ").strip() print ans if ans != str(m): print("Wrong !!") exit(0) print flag except Exception: print("Error occurred") exit(0)
def generate_safe_prime(nbits): """ Finds a safe prime of nbits using probabilistic method rather than deterministic; because a large prime number is required. """ q = number.getRandomNBitInteger(nbits) while not gmpy.is_prime(q): q = gmpy.next_prime(q) return int(q)
def create_boggarts(fear, danger): # for each level of danger we're increasing fear while danger > 0: fear = next_prime(fear) if getrandbits(1): yield fear danger -= 1
def getPrimes(moduleDigits): prime_list = [] x = 1 # Agafem el ultim primer amb un menor numero de digits while len(str(x)) < moduleDigits: x = gmpy.next_prime(x) x = gmpy.next_prime(x) while len(str(x)) < moduleDigits + 1: prime_list.append(str(x)[:]) x = gmpy.next_prime(x) return int(''.join(random.sample(prime_list, 1)))
def gen_prime(): from ecpy.util import is_prime from random import randint while True: p = int(next_prime(randint(2**(bits - 1), 2**bits))) if is_prime(p * 6 - 1): break return p * 6 - 1, p
def p_gen(): small_p = mpz(1) k = P_SIZE while True: small_p = gmpy.next_prime(small_p) p = small_p ** int(k / (small_p.bit_length() - 1)) yield p k *= 2
def get_primes(self, min, max): primes = [] while True: prime = int(gmpy.next_prime(min)) if prime <= max: primes += [prime] min = prime else: return primes
def make_participants_key(l, nbit): while True: p, q = getPrime(nbit), getPrime(nbit) N, phi = p * q, (p-1)*(q-1) x = random.randint(1, N) if (N % 8 == 1) and (phi % 8 == 4) and (p != q): if pow(q ** 2 * x, (p-1)/2, p) + pow(p ** 2 * x, (q-1)/2, q) == N - phi - 1: break participants_key = [] r, s = [getPrime(nbit) for _ in '01'] for i in range(l): u, v = gmpy.next_prime(r), gmpy.next_prime(s) u -= u % 4 v -= v % 8 participants_key.append((long(u), long(v))) r, s = u + 2 * v, v + 3 * u e0 = phi + sum([participants_key[i][0] for i in range(len(participants_key))]) + sum([participants_key[i][1] for i in range(len(participants_key))])
def ext_rsa_decrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1) * (q - 1) d = gmpy.invert(e, phi) privatekey = RSA.construct( (long(n), long(e), long(d), long(p), long(q))) key = PKCS1_v1_5.new(privatekey) de_error = '' enc = key.decrypt(msg.decode('base64'), de_error) return enc except Exception as error: print error p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2 * p * q) e = gmpy.next_prime(e**2)
def get_prime(size=128, rnd=random.SystemRandom, k=DEFAULT_ITERATION, algorithm=None): if callable(rnd): rnd = rnd() while True: n = rnd.getrandbits(size-2) n = 2 ** (size-1) + n * 2 + 1 if is_prime(n, rnd=rnd, k=k, algorithm=algorithm): return n if algorithm == 'gmpy-miller-rabin': return gmpy.next_prime(n)
def squbes(): last_prime = 2 last_it = sq(last_prime) h = HeapIter(last_it) for s, it in h: yield s if it == last_it: last_prime = int(next_prime(last_prime)) last_it = sq(last_prime) h.add(last_it)
def calculate_division(test, n): # print n # print 'number of digits in test is {} in base 2'.format(_g.numdigits(test,2)) # print 'number of digits in n is {} in base 2'.format(_g.numdigits(n,2)) prime = _g.next_prime(test) # print prime if _g.is_prime(prime): # print 'I got a prime {}'.format(prime) if n % prime == 0: print n print 'success'
def brute_find2(i, t = 20): j = 0 n_i = n[i] c_i = c_int[i] e_i = e[i] for i in range(2**t): j = gmpy.next_prime(j) g, d, y = xgcd(j, n_i) if g != 1: print j return j pass
def setup(): """Computes a (public, private)-keypair. >>> (publickey, secretkey) = ShoupProtocol.setup() """ # generate the primes p = 0 while p % 4 != 3: p = random.SystemRandom().getrandbits(1024) p = int(gmpy.next_prime(p)) q = 4 while q % 4 != 3: q = random.SystemRandom().getrandbits(1024) q = int(gmpy.next_prime(q)) n = p * q # search for a quadratic residue mod n y = random.SystemRandom().getrandbits(1024) % n y = pow(y, 2, n) publickey = (y, n) secretkey = (p, q) return (publickey, secretkey)
def setup(): """Computes a (public, private)-keypair. >>> (publickey, secretkey) = GQProtocol.setup() """ # generate the primes p = random.SystemRandom().getrandbits(1024) p = int(gmpy.next_prime(p)) q = random.SystemRandom().getrandbits(1024) q = int(gmpy.next_prime(q)) n = p * q e = 65537 J = random.SystemRandom().getrandbits(2048) while J > n: J = random.SystemRandom().getrandbits(2048) publickey = (J, e, n) # compute the private key d = gmpy.invert(e, (p - 1) * (q - 1)) B = pow(gmpy.invert(J, n), d, n) secretkey = (B, d) return (publickey, secretkey)
def alg_231(n, improved=True): """ Page 197: Trial Division """ # [1] t = 0 k = 2 dk = 2 sqrt_n = math.sqrt(n) count = 0 while True: if count > sqrt_n: break if int(n) == 1: break # [2] if improved: dk = int(gmpy.next_prime(dk)) # [3] if improved: q = n / dk r = n % dk else: q = n / k r = n % k if r != 0: if improved: if q > dk: k += 1 else: t += 1 pt = n else: if q > k: # [4] k += 1 else: t += 1 pt = n else: t += 1 if improved: pt = dk else: pt = k n = q break count += 1 # print( q, r ) print(n, pt)
def brute_find2(i, t=20): j = 0 n_i = n[i] c_i = c_int[i] e_i = e[i] for i in range(2**t): j = gmpy.next_prime(j) g, d, y = xgcd(j, n_i) if g != 1: print j return j pass
def count_safe_primes(bits): randfunc = Crypto.Random.new().read started = time.time() ret = [] while True: r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc)) q = gmpy.next_prime(r) p = 2*q + 1 germain = gmpy.is_prime(p) ret.append((germain, int(q - r))) if time.time() - started > 60: break return ret
def pf( _num, _pf=[], _p=2 ): "returns the prime factorization of _num" assert _num >= 2 if is_prime(_num): _pf.append(_num) return _pf if _num % _p == 0: _pf.append(_p) return pf( _num / _p, _pf ) else: return pf( _num, _pf, next_prime( _p ) )
def factors(n, veb, ra, ov, pr): '''Generates factors of n. Strips small primes, then feeds to ecm function. Input: n -- An integer to factor veb -- If True, be verbose ra -- If True, select sigma values randomly ov -- How asymptotically fast the calculation is pr -- What portion of the total processing power this run gets Output: Factors of n, via a generator. Notes: 1. A good value of ov for typical numbers is somewhere around 10. If this parameter is too high, overhead and memory usage grow. 2. If ra is set to False and veb is set to True, then results are reproducible. If ra is set to True, then one number may be done in parallel on disconnected machines (at only a small loss of efficiency, which is less if pr is set correctly).''' if type(n) not in T: raise ValueError, 'Number given must be integer or long.' if not 0 < pr <= 1: yield 'Error: pr must be between 0 and 1' return while not n & 1: n >>= 1 yield 2 n = mpz(n) k = inv_const(n) prime = 2 trial_division_bound = max(10 * k**2, 100) while prime < trial_division_bound: prime = next_prime(prime) while not n % prime: n /= prime yield prime if isprime(n): yield n return if n == 1: return for factor in ecm(n, ra, ov, veb, trial_division_bound, pr): yield factor
def decrypt_RSA(cipherfile): n = 98099407767975360290660227117126057014537157468191654426411230468489043009977 e = 12405943493775545863 p = 311155972145869391293781528370734636009 q = 315274063651866931016337573625089033553 cipher = open(cipherfile, "r").read() while True: try: # key = open(privkey, "r").read() phi = (p - 1) * (q - 1) d = gmpy.invert(e, phi) # pubkey = RSA.construct((long(n), long(e))) privkey = RSA.construct((long(n), long(e), long(d))) key = PKCS1_v1_5.new(privkey) decrypted = key.decrypt(base64.b64decode(cipher), None) print decrypted break except Exception as ex: print ex p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2 * p * q) e = gmpy.next_prime(e**2) n = long(p) * long(q)
def El_Gamal_ParamGen(): p = 4 while not gmpy.is_prime(p): r = randint(0, 2**64) q = gmpy.next_prime(2**64 + r) p = 2 * q + 1 g_prime = randint(1, int(p - 1)) g = pow(g_prime, 2, p) # generator of the group assert pow(g, q, p) == 1 G = g, p, q x = randint(1, int(q - 1)) # secret key y = pow(g, x, p) # public key pk = El_Gamal_PublicKey(G, y) sk = El_Gamal_SecretKey(G, x) return pk, sk
def get_prime(size=128, rnd=default_crypto_random, k=DEFAULT_ITERATION, algorithm=None): '''Generate a prime number of the giver size using the is_prime() helper function. size - size in bits of the prime, default to 128 rnd - a random generator to use k - the number of iteration to use for the probabilistic primality algorithms, algorithm - the name of the primality algorithm to use, default is the probabilistic Miller-Rabin algorithm. Return value: a prime number, as a long integer ''' while True: n = rnd.getrandbits(size-2) n = 2 ** (size-1) + n * 2 + 1 if is_prime(n, rnd=rnd, k=k, algorithm=algorithm): return n if algorithm == 'gmpy-miller-rabin': return gmpy.next_prime(n)
def __init__(self, engine=None, parameter=10000, shared=None): super(SmallFactor,self).__init__(engine, parameter, shared) connection = self.engine.connect() s = select([db.smallFactorTable.c.product]).where(db.smallFactorTable.c.up_to==self.parameter) res = connection.execute(s).first() if res is None: n = 2 self.product = mpz('1') while n < self.parameter: self.product = self.product * n n = gmp.next_prime(n) connection.execute(db.smallFactorTable.insert(), up_to=self.parameter, product = str(self.product)) else: self.product = mpz(res[0])
def find_random_prime(k): """Find a random *k* bit prime number. The prime has exactly *k* significant bits: @type k: int @param k: number of significant bits @rtype: mpz @return: prime number >>> 2 <= _find_random_prime(10) < 2**10 True """ while True: prime = gmpy.next_prime(rand.randint(2**(k - 1), 2**k - 1)) if prime < 2**k: return prime
def isprime(n): ''' Tests for primality of n trying first fastprime and then a slower but accurate algorithm. Time complexity is O(N**3) (assuming quadratic multiplication), where n has N digits. Returns the primality of n (True or False).''' if not fastprime(n): return False elif n < SMALLEST_COUNTEREXAMPLE_FASTPRIME: return True do_loop = False j = 1 d = n >> 1 a = 2 bound = int(0.75 * math.log(math.log(n)) * math.log(n)) + 1 while not d & 1: d >>= 1 j += 1 while a < bound: a = next_prime(a) p = atdn(a, d, n) if p == 1 or p == n - 1: continue for _ in xrange(j): p = (p * p) % n if p == 1: return False elif p == n - 1: do_loop = True break if do_loop: do_loop = False continue return False return True
def elgamal_param_gen(): """Generate an El Gamal keypair :rtype: (ElgamalPublicKey, ElgamalSecretKey) """ p = 4 while not gmpy.is_prime(p): r = randint(0, 2**64) q = gmpy.next_prime(2**64 + r) p = 2 * q + 1 g_prime = randint(1, int(p - 1)) g = pow(g_prime, 2, p) # generator of the group assert pow(g, q, p) == 1 G = g, p, q x = randint(1, int(q - 1)) # secret key y = pow(g, x, p) # public key pk = ElgamalPublicKey(G, y) sk = ElgamalSecretKey(G, x) return pk, sk
def build_key(bits=2048, e=65537, embed='', pos=1, randfunc=None): # generate base key rsa = RSA.generate(bits, randfunc) # extract modulus as a string n_str = unhexlify(str(hex(rsa.n))[2:]) # print(str(hex(rsa.n)), n_str) # embed data into the modulus n_hex = hexlify(replace_at(n_str, embed, pos)) n = gmpy.mpz(n_hex, 16) p = rsa.p # compute a starting point to look for a new q value pre_q = n / p # use the next prime as the new q value q = gmpy.next_prime(gmpy.mpz(pre_q)) n = p * q phi = (p-1) * (q-1) # compute new private exponent d = gmpy.invert(e, phi) # make sure that p is smaller than q if p > q: (p, q) = (q, p) return RSA.construct((int(n), int(e), int(d), int(p), int(q)))
def factorize(x): r''' >>> factorize(a) [3, 41] >>> factorize(b) [2, 2, 2, 3, 19] >>> ''' savex=x prime=2 x=_g.mpz(x) factors=[] while x>=prime: newx,mult=x.remove(prime) if mult: factors.extend([int(prime)]*mult) x=newx prime=_g.next_prime(prime) for factor in factors: assert _g.is_prime(factor) from operator import mul from functools import reduce assert reduce(mul, factors)==savex return factors
def factorize(x=c): r''' (Takes about 25ms, on c, on a first-generation Macbook Pro) >>> factorize(a) [3, 41] >>> factorize(b) [2, 2, 2, 3, 19] >>> ''' import gmpy as _g savex=x prime=2 x=_g.mpz(x) factors=[] while x>=prime: newx,mult=x.remove(prime) if mult: factors.extend([int(prime)]*mult) x=newx prime=_g.next_prime(prime) for factor in factors: assert _g.is_prime(factor) from operator import mul assert reduce(mul, factors)==savex return factors
def schoof(F, E): def y2_reduce(pol, x, y, Fx): ''' Reduce `pol` modulo (y^2 - Fx) <=> pol over F_q[x, y] / (y^2 - Fx) ''' if pol.degree() < 2: return pol assert all([len(t) == 1 and t[0] == 0 for t in pol[1::2]]) for i in xrange(1, (len(pol) - 1) // 2 + 1): y2 = (sum(map(lambda t: x**t[0] * t[1], enumerate(pol[2 * i])))) pol = pol - (y**(2*i) * y2) + (y2 * Fx ** i) return pol @memoize def division_polynomial(ell, x, y): pol = torsion_polynomial(ell, E, x, y) pol.trim() return pol def get_polynomial(ell, x0, y0): if ell == 0: return PU.element_class(PU, [0]) pp0 = division_polynomial(ell, x0, y0) pm1 = division_polynomial(ell - 1, x0, y0) pp1 = division_polynomial(ell + 1, x0, y0) pol_p = x - (pm1 * pp1) pol_q = pp0 ** 2 pol_p = y2_reduce(pol_p, x, y, Fx) pol_q = y2_reduce(pol_q, x, y, Fx) pol_p = (pol_p.apply(xs, 0)) pol_q = (pol_q.apply(xs, 0)) pol = pol_p / pol_q if not isinstance(pol, UnivariatePolynomialRing): return PU.element_class(PU, [pol]) return pol L = 2 N = 1 t = {} factors = {} q = F.p ** F.degree() PR = BivariatePolynomialRing(F, ['x', 'y']) PU = UnivariatePolynomialRing(F, 'xs') x, y = PR.gens() Fx = x**3 + E.a*x + E.b xs = PU.gen() while N < math.sqrt(F.n) * 4: L = int(gmpy.next_prime(L)) qbar = q % L mod_poly = division_polynomial(L, x, y).apply(xs, 0) poly1 = get_polynomial(qbar + 1, x, y) % mod_poly for tbar in xrange(0, L): poly2 = get_polynomial(tbar, x, y) % mod_poly if poly1 == poly2: factors[L] = tbar N *= L break print(factors) t = crt(map(lambda x: factors[x], factors.keys()), factors.keys()) if t > N // 2: t = - (N - t) return q + 1 - t
flag = '[censored]' P = [] Q = [] D = [] N = [] pubKey = [] privKey = [] Enc = [] p = random.randint(1 << 510, 1 << 511) q = random.randint(1 << 510, 1 << 511) for i in range(0, 3): p = gmpy.next_prime(p) q = gmpy.next_prime(q) P.append(p) Q.append(q) for i in range(0, 3): N.append(P[i] * Q[2 - i]) print N[i] D.append(long(gmpy.invert(long(65537), (P[i] - 1) * (Q[2 - i] - 1)))) privKey.append(RSA.construct((long(N[i]), long(65537), long(D[i]), long(P[i]), long(Q[2 - i])))) pubKey.append(RSA.construct((long(N[i]), long(65537)))) print pubKey[i].exportKey() key = PKCS1_v1_5.new(pubKey[i]) Enc.append(base64.b64encode(key.encrypt(flag[19 * i : 19 * (i + 1)]))) print Enc[i]
from gmpy import next_prime, is_prime def truncatable(_s): s = str(_s) l = len(s) for i in range(l): if not is_prime(int(s[i:])): return False if not is_prime(int(s[: i + 1])): return False return True if __name__ == "__main__": primes = [] p = 7 while len(primes) < 11: p = next_prime(p) if truncatable(p): primes.append(p) print(sum(primes))
def sign(msg, p, q, x, k, n): w = int(math.ceil(float((hash(msg) - pow(x, k, n)) % n) / float(p * q))) y = (w * gmpy.invert((k * pow(x, k - 1)), p)) % p s = (x + (y * p * q)) % n return s def verify(msg, s, k, n): u = pow(s, k, n) z = hash(msg) zp = z + pow(2, int(math.ceil(float(math.log(n, 2) * 2.0 / 3.0)))) if (u >= z) and (zp >= u): return True else: return False p = int(gmpy.next_prime(30000)) q = int(gmpy.next_prime(25000)) n = pow(p, 2) * q k = 12 x = 4321 x = 14 # p = 285311670673 # q = 387420499 # n = pow(p, 2) * q # k = 7 # msg = 31111133 # x = 45767
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 primes(limit): prime = 2 while prime < limit: yield prime prime = gmpy.next_prime(prime)
if __name__ == "__main__": # # finds the greatest length cycle in 1/(2..999), # but success is based on precision. higher precision = longer # running time. # precision = 1000 # set the precision of division getcontext().prec = precision max = (0,0,"") i = 2 while i < 1000: s = str( Decimal(1) / Decimal(int(i)) )[2:] seq = get_cycle(s) if len(seq) > len(max[2]): max = (i,s,seq) i = next_prime(i) for el in max: print(el) # max = 0 # # for i in xrange(2,1000): # if is_prime(i): # max = max if max > i-1 else i-1
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
import gmpy import itertools from gmpy import mpz, mpq limit = 10 maxN = 0 """ once n_count reaches million, we can assume we've generated all unique n <= million using primes """ n_count = 0 primes = (gmpy.next_prime(n) for n in range(1, limit)) print(type(primes)) exit() """ we want to generate all unique n as quickly as possible. to avoid duplicate factorizations, keep records of all distinct prime combinations tried """ tried_combos = {} """ n -> phi(n) """ pairs = {} # generate primes for n in range(1, limit): nextPrime = gmpy.next_prime(n) primes.append(nextPrime)