def main4(): print(crack_when_pq_close(23360947609)) p = next_prime(2**128) print(p) q = next_prime(p) print(q) print(crack_when_pq_close(p * q))
def generate_pseudoprime(bases, min_bitsize=0): """ Generates a pseudoprime which passes the Miller-Rabin primality test for the provided bases. :param bases: the bases :param min_bitsize: the minimum bitsize of the generated pseudoprime (default: 0) :return: a tuple containing the pseudoprime, as well as its 3 prime factors """ bases.sort() k2 = next_prime(bases[-1]) k3 = next_prime(k2) while True: residues = [inverse_mod(-k2, k3), inverse_mod(-k3, k2)] moduli = [k3, k2] s = _generate_s(bases, k2, k3) residue, modulus = _backtrack(s, bases, residues, moduli, 0) if residue and modulus: i = (2 ** (min_bitsize // 3)) // modulus while True: p1 = residue + i * modulus p2 = k2 * (p1 - 1) + 1 p3 = k3 * (p1 - 1) + 1 if is_prime(p1) and is_prime(p2) and is_prime(p3): return p1 * p2 * p3, p1, p2, p3 i += 1 else: k3 = next_prime(k3)
def main7(): set_random_seed(0) p = next_prime(randrange(2**96)) q = next_prime(randrange(2**97)) n = p * q print(p, q, n) print(qsieve(n))
def make_hash(p, N1, N2, np=20): plist = [next_prime(400000)] while len(plist) < np: plist.append(next_prime(plist[-1])) hashtab = {} nc = 0 for E in cremona_optimal_curves(srange(N1, N2 + 1)): nc += 1 h = hash1(p, E, plist) lab = E.label() if nc % 1000 == 0: print(lab) #print("{} has hash = {}".format(lab,h)) if h in hashtab: hashtab[h].append(lab) #print("new set {}".format(hashtab[h])) else: hashtab[h] = [lab] ns = 0 for s in hashtab.values(): if len(s) > 1: ns += 1 #print s print("{} sets of conjugate curves".format(ns)) return hashtab
def make_hash_many(plist, N1, N2, nq=20): qlist = [next_prime(400000)] while len(qlist) < nq: qlist.append(next_prime(qlist[-1])) hashtabs = dict([(p, dict()) for p in plist]) nc = 0 for E in cremona_optimal_curves(srange(N1, N2 + 1)): nc += 1 lab = E.label() if nc % 1000 == 0: print(lab) h = hash1many(plist, E, qlist) for p in plist: hp = h[p] if hp in hashtabs[p]: hashtabs[p][hp].append(lab) print("p={}, new set {}".format(p, hashtabs[p][hp])) else: hashtabs[p][hp] = [lab] ns = dict([(p, len([v for v in hashtabs[p].values() if len(v) > 1])) for p in plist]) for p in plist: print("p={}: {} nontrivial sets of congruent curves".format(p, ns[p])) return hashtabs
def make_base_field(self): if self.args.base_field != None: F = GF(self.args.base_field, 'F') self.field_traits.check(F) return F p = next_prime(2**self.args.num_bits) while not self.field_traits.check(GF(p, 'F'), nothrow=True): p = next_prime(p) return GF(p, 'F')
def rsa(bits): # only prove correctness up to 1024bits proof = (bits <= 1024) p = next_prime(ZZ.random_element(2**(bits // 2 + 1)), proof=proof) q = next_prime(ZZ.random_element(2**(bits // 2 + 1)), proof=proof) n = p * q phi_n = (p - 1) * (q - 1) while True: e = ZZ.random_element(1, phi_n) if gcd(e, phi_n) == 1: break d = lift(Mod(e, phi_n)**(-1)) return e, d, n
def make_hash_SW(plist, N1=0, N2=999, nq=30, tate=False): """Here N1 and N2 are in [0..999] and refer to the batch number, where batch n has curves of conductor between n*10^5 and (n+1)*10^5 plist is a list of primes so we can make several hash tables in parallel If tate=True then ignore curves unless ord_p(j(E))=-1 """ # Compute the first nq primes greater than the largest conductor: qlist = [next_prime((N2 + 1) * 10**5)] while len(qlist) < nq: qlist.append(next_prime(qlist[-1])) # Initialize hash tables for each p: hashtabs = dict([(p, dict()) for p in plist]) nc = 0 for N in range(N1, N2 + 1): print("Batch {}".format(N)) for dat in SteinWatkinsAllData(N): nc += 1 NE = dat.conductor E = EllipticCurve(dat.curves[0][0]) assert E.conductor() == NE if tate and all(E.j_invariant().valuation(p) >= 0 for p in plist): continue lab = SW_label(E) if nc % 10000 == 0: print(lab) # if nc>10000: # break h = hash1many(plist, E, qlist) for p in plist: if tate and E.j_invariant().valuation(p) >= 0: continue hp = h[p] if hp in hashtabs[p]: hashtabs[p][hp].append(lab) print("p={}, new set {}".format(p, hashtabs[p][hp])) else: hashtabs[p][hp] = [lab] ns = dict([(p, len([v for v in hashtabs[p].values() if len(v) > 1])) for p in plist]) for p in plist: print("p={}: {} nontrivial sets of congruent curves".format(p, ns[p])) return hashtabs
def __init__(self, signature=0, weight=2, level_limit=34, rank_limit=4, primes=None, simple_color=None, nonsimple_color=None, reduction=True, bound=0): """ Initialize a SimpleModulesGraph containing finite quadratic modules of signature ``signature``. They are checked for being ``weight``-simple if their minimal number of generators is at most `rank_limit`. INPUT: - ``signature``: the signature of the modules - ``weight``: check for cusp forms of weight ``weight`` - ``level_limit``: only check for anisotropic modules with level smaller than ``level_limit`` - ``rank_limit``: an upper bound for the minimal number of generators - ``bound``: upper bound for the dimension (for considered being simple), default=0 OUTPUT: A SimpleModulesGraph object. No computations are done after initialization. Start the computation using the method ``compute()``. """ ########################### # basic parameters ########################### self._level_limit = Integer(level_limit) self._rank_limit = Integer(rank_limit) self._signature = Integer(signature) % 8 self._weight = QQ(weight) self._reduction = reduction self._bound = bound ######################################################### # Initialize the primes that need to be checked # According to Theorem 4.21 in [BEF], # in the worst case, we need to check primes p for which # prime_pol_simple(p, weight) <= bound. ######################################################### if primes is None: p = 2 while True: if prime_pol_simple(p, weight) > self._bound: primes = list(prime_range(p)) break else: p = next_prime(p) self._primes = primes self._simple_color = colors.darkred.rgb( ) if simple_color is None else simple_color self._nonsimple_color = colors.darkgreen.rgb( ) if nonsimple_color is None else nonsimple_color self._vertex_colors = dict() self._vertex_colors[self._simple_color] = list() self._vertex_colors[self._nonsimple_color] = list() self._heights = dict() # a height function for plotting self._simple = list() # will contain the list of k-simple modules super(SimpleModulesGraph, self).__init__()
def _rank(self, v): r""" Return a lower bound for the rank of the matrix U. """ self._U[self._U_rank] = v K = self._U.base_ring() if K is QQ: return self._U.rank() k = K.residue_field(self._good_prime) try: self._Ubar[self._U_rank] = v.change_ring(k) except ValueError: # Some denominator in v is not a unit mod q. while True: from sage.all import next_prime self._good_prime = next_prime(self._good_prime.residue_field().characteristic()) self._good_prime = K.ideal(self._good_prime).factor()[0][0] k = K.residue_field(self._good_prime) try: self._Ubar = self._U.change_ring(k) except ValueError: continue if self._Ubar.rank() == self._U_rank + 1: return self._U_rank + 1 return self._U_rank
def gen_instance(n, q, h, alpha=None, m=None, seed=None, s=None): """ Generate FHE-style LWE instance :param n: dimension :param q: modulus :param alpha: noise rate (default: 8/q) :param h: hamming weight of the secret (default: 2/3n) :param m: number of samples (default: n) """ if seed is not None: set_random_seed(seed) q = next_prime(ceil(q) - 1, proof=False) if alpha is None: stddev = 3.2 else: stddev = alpha * q / sqrt(2 * pi) #RR = parent(alpha*q) #stddev = alpha*q/RR(sqrt(2*pi)) if m is None: m = n K = GF(q, proof=False) while 1: A = random_matrix(K, m, n) if A.rank() == n: break if s is not None: c = A * s else: if h is None: s = random_vector(ZZ, n, x=-1, y=1) else: S = [-1, 1] s = [S[randint(0, 1)] for i in range(h)] s += [0 for _ in range(n - h)] shuffle(s) s = vector(ZZ, s) c = A * s D = DiscreteGaussian(stddev) for i in range(m): c[i] += D() u = random_vector(K, m) print '(A, c) is n-dim LWE samples (with secret s) / (A, u) is uniform samples' return A, c, u, s
def experiment(n=65, q=next_prime(ceil(2**9)), sigma=8, m=178, block_size=56, tours=6): alpha = sigma / q L, e = gen_instance(n, alpha, q, m) R, norms = run_instance(L, block_size, tours, e) return L, R, e, norms
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime rec = self.get_db_record() if rec is None: return 0 prec_in_db = rec.get('prec') return next_prime(prec_in_db) - 1
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime rec = self.get_db_record() if rec is None: return 0 prec_in_db = rec.get('prec') return next_prime(prec_in_db)-1
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime prec_in_db = list(self._file_collection.find(self.key_dict(), ['prec'])) if len(prec_in_db) == 0: return 0 max_prec_in_db = max(r['prec'] for r in prec_in_db) return next_prime(max_prec_in_db)-1
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime recs = self._collection.find({'hecke_orbit_label':self.hecke_orbit_label}) if recs.count()==0: return 0 prec_in_db = max(rec['prec'] for rec in recs) return next_prime(prec_in_db)-1
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime recs = self._file_collection.find(self.key_dict()) if recs is None: return 0 prec_in_db = max(rec['prec'] for rec in recs) return next_prime(prec_in_db)-1
def max_coefficient_in_db(self): r""" Check how many coefficients we can generate from the eigenvalues in the database. """ from sage.all import next_prime recs = self._collection.find( {'hecke_orbit_label': self.hecke_orbit_label}) if recs.count() == 0: return 0 prec_in_db = max(rec['prec'] for rec in recs) return next_prime(prec_in_db) - 1
def __init__(self, surface): if isinstance(surface, TranslationSurface): base_ring = surface.base_ring() from flatsurf.geometry.pyflatsurf_conversion import to_pyflatsurf self._surface = to_pyflatsurf(surface) else: from flatsurf.geometry.pyflatsurf_conversion import sage_base_ring base_ring, _ = sage_base_ring(surface) self._surface = surface # A model of the vector space R² in libflatsurf, e.g., to represent the # vector associated to a saddle connection. self.V2 = pyflatsurf.vector.Vectors(base_ring) # We construct a spanning set of edges, that is a subset of the # edges that form a basis of H_1(S, Sigma; Z) # It comes together with a projection matrix t, m = self._spanning_tree() assert set(t.keys()) == set(f[0] for f in self._faces()) self.spanning_set = [] v = set(t.values()) for e in self._surface.edges(): if e.positive() not in v and e.negative() not in v: self.spanning_set.append(e) self.d = len(self.spanning_set) assert 3*self.d - 3 == self._surface.size() assert m.rank() == self.d m = m.transpose() # projection matrix from Z^E to H_1(S, Sigma; Z) in the basis # of spanning edges self.proj = matrix(ZZ, [r for r in m.rows() if not r.is_zero()]) self.Omega = self._intersection_matrix(t, self.spanning_set) self.V = FreeModule(self.V2.base_ring(), self.d) self.H = matrix(self.V2.base_ring(), self.d, 2) for i in range(self.d): s = self._surface.fromHalfEdge(self.spanning_set[i].positive()) self.H[i] = self.V2._isomorphic_vector_space(self.V2(s)) self.Hdual = self.Omega * self.H # Note that we don't use Sage vector spaces because they are usually # way too slow (in particular we avoid calling .echelonize()) self._U = matrix(self.V2._algebraic_ring(), self.d) if self._U.base_ring() is not QQ: from sage.all import next_prime self._good_prime = self._U.base_ring().ideal(next_prime(2**30)).factor()[0][0] self._Ubar = matrix(self._good_prime.residue_field(), self.d) self._U_rank = 0 self.update_tangent_space_from_vector(self.H.transpose()[0]) self.update_tangent_space_from_vector(self.H.transpose()[1])
def dirichlet(R, euler_factors): PS = PowerSeriesRing(R) pef = zip(primes_first_n(len(euler_factors)), euler_factors) an_list_bound = next_prime(pef[-1][0]) res = [1]*an_list_bound for p, ef in pef: k = RR(an_list_bound).log(p).floor()+1 foo = (1/PS(ef)).padded_list(k) for i in range(1, k): res[p**i] = foo[i] extend_multiplicatively(res) return res
def get_frob_list_HyperellipticCurve(f, h, bound=100): C = HyperellipticCurve(f, h) frob_list = [] p = 2 while p < bound: try: f = C.change_ring(GF(p)).frobenius_polynomial() if f.degree() == 2 * C.genus(): frob_list.append([p, f.reverse()]) except: pass p = next_prime(p) return frob_list
def __init__(self, signature=0, weight=2, level_limit=34, rank_limit=4, primes=None, simple_color=None, nonsimple_color=None, reduction=True, bound=0): """ Initialize a SimpleModulesGraph containing finite quadratic modules of signature ``signature``. They are checked for being ``weight``-simple if their minimal number of generators is at most `rank_limit`. INPUT: - ``signature``: the signature of the modules - ``weight``: check for cusp forms of weight ``weight`` - ``level_limit``: only check for anisotropic modules with level smaller than ``level_limit`` - ``rank_limit``: an upper bound for the minimal number of generators - ``bound``: upper bound for the dimension (for considered being simple), default=0 OUTPUT: A SimpleModulesGraph object. No computations are done after initialization. Start the computation using the method ``compute()``. """ ########################### # basic parameters ########################### self._level_limit = Integer(level_limit) self._rank_limit = Integer(rank_limit) self._signature = Integer(signature) % 8 self._weight = QQ(weight) self._reduction = reduction self._bound = bound ######################################################### # Initialize the primes that need to be checked # According to Theorem 4.21 in [BEF], # in the worst case, we need to check primes p for which # prime_pol_simple(p, weight) <= bound. ######################################################### if primes is None: p = 2 while True: if prime_pol_simple(p, weight) > self._bound: primes = list(prime_range(p)) break else: p = next_prime(p) self._primes = primes self._simple_color = colors.darkred.rgb() if simple_color is None else simple_color self._nonsimple_color = colors.darkgreen.rgb() if nonsimple_color is None else nonsimple_color self._vertex_colors = dict() self._vertex_colors[self._simple_color] = list() self._vertex_colors[self._nonsimple_color] = list() self._heights = dict() # a height function for plotting self._simple = list() # will contain the list of k-simple modules super(SimpleModulesGraph, self).__init__()
def verify_curve(g, factorsRR_geom, bound = 300, RM_coeff = None): D = ZZ(g.discriminant()); C = HyperellipticCurve(g) p = 3; ef = []; while p < bound: if D.mod(p) != ZZ(0): ef += [C.change_ring(GF(p)).frobenius_polynomial().list()] ef[-1].reverse() p = next_prime(p) rank_euler, _ = upperrank(ef) rank_endo = rank_from_endo(factorsRR_geom) if factorsRR_geom == ['RR', 'RR'] and RM_coeff is not None: checkRM = RM_and_notCM(ef, RM_coeff) return rank_endo == rank_euler and checkRM, rank_endo, rank_euler else: return rank_endo == rank_euler, rank_endo, rank_euler
def central_character_as_artin_rep(self): """ Returns the central character, i.e., determinant character as a web character, but as an Artin representation """ if self.dimension() == 1: return self if 'central_character_as_artin_rep' in self._data: return self._data['central_character_as_artin_rep'] return ArtinRepresentation(self._data['Dets'][self.galorbindex() - 1]) myfunc = self.central_char_function() # Get the Artin field nfgg = self.number_field_galois_group() # Get its artin reps arts = nfgg.ArtinReps() # Filter for 1-dim arts = [ a for a in arts if ArtinRepresentation(str(a['Baselabel']) + "c1").dimension() == 1 ] artfull = [ ArtinRepresentation(str(a['Baselabel']) + "c" + str(a['GalConj'])) for a in arts ] # hold = artfull # Loop as we evaluate at primes until there is only one left # Fix the return value to be what we want artfull = [[a, a.central_char_function(), 2 * a.character_field()] for a in artfull] n = 2 * self.character_field() p = 2 hard_primes = self.hard_primes() while len(artfull) > 1: if p not in hard_primes: k = 0 while k < len(artfull): if n * artfull[k][1]( p, artfull[k][2]) == artfull[k][2] * myfunc(p, n): k += 1 else: # Quick deletion of k-th term artfull[k] = artfull[-1] del artfull[-1] p = next_prime(p) self._data['central_character_as_artin_rep'] = artfull[0][0] return artfull[0][0]
def gen_fhe_instance(n, q, alpha=None, h=None, m=None, seed=None): """ Generate FHE-style LWE instance :param n: dimension :param q: modulus :param alpha: noise rate (default: 8/q) :param h: hamming weight of the secret (default: 2/3n) :param m: number of samples (default: n) """ if seed is not None: set_random_seed(seed) q = next_prime(ceil(q)-1, proof=False) if alpha is None: alpha = ZZ(8)/q n, alpha, q = preprocess_params(n, alpha, q) stddev = stddevf(alpha*q) if m is None: m = n K = GF(q, proof=False) A = random_matrix(K, m, n) if h is None: s = random_vector(ZZ, n, x=-1, y=1) else: S = [-1, 1] s = [S[randint(0, 1)] for i in range(h)] s += [0 for _ in range(n-h)] shuffle(s) s = vector(ZZ, s) c = A*s D = DiscreteGaussian(stddev) for i in range(m): c[i] += D() return A, c
def gen_fhe_instance(n, q, alpha=None, h=None, m=None, seed=None): """ Generate FHE-style LWE instance :param n: dimension :param q: modulus :param alpha: noise rate (default: 8/q) :param h: hamming weight of the secret (default: 2/3n) :param m: number of samples (default: n) """ if seed is not None: set_random_seed(seed) q = next_prime(ceil(q) - 1, proof=False) if alpha is None: alpha = ZZ(8) / q n, alpha, q = preprocess_params(n, alpha, q) stddev = stddevf(alpha * q) if m is None: m = n K = GF(q, proof=False) A = random_matrix(K, m, n) if h is None: s = random_vector(ZZ, n, x=-1, y=1) else: S = [-1, 1] s = [S[randint(0, 1)] for i in range(h)] s += [0 for _ in range(n - h)] shuffle(s) s = vector(ZZ, s) c = A * s D = DiscreteGaussian(stddev) for i in range(m): c[i] += D() return A, c
def InsolublePlaces(f,h=0): # List of primes at which the curve y²+h(x)*y=f(x) is not soluble # Assumes f and h have integer coefficients S = [] # List of primes at which not soluble # Get eqn of the form y²=F(x) F = f if h: F = 4*f + h**2 # Do we have a rational point an Infty ? if F.degree()%2 or F.leading_coefficient().is_square(): return [] # Treat case of RR if F.leading_coefficient() < 0 and F.number_of_real_roots() == 0: S.append(0) # Remove squares from lc(F) d = F.degree() lc = F.leading_coefficient() t = F.variables()[0] a = lc.squarefree_part() # lc/a is a square a = lc//a Zx = PolynomialRing(ZZ,'x') F = Zx(a**(d-1) * F(t/a)) # Find primes of bad reduction for our model D = F.disc() P = Set(D.prime_divisors()) # Add primes at which Weil bounds do not guarantee a mod p point g = (d-2)//2 Weil = [] p = 2 while (p+1)**2 <= 4 * g**2 * p: Weil.append(p) p = next_prime(p) P = P.union(Set(Weil)) # Test for solubility for p in P: if not IsSolubleAt(F,p): S.append(p) S.sort() return S
def InsolublePlaces(f, h=0): # List of primes at which the curve y²+h(x)*y=f(x) is not soluble # Assumes f and h have integer coefficients S = [] # List of primes at which not soluble # Get eqn of the form y²=F(x) F = f if h: F = 4 * f + h**2 # Do we have a rational point an Infty ? if F.degree() % 2 or F.leading_coefficient().is_square(): return [] # Treat case of RR if F.leading_coefficient() < 0 and F.number_of_real_roots() == 0: S.append(0) # Remove squares from lc(F) d = F.degree() lc = F.leading_coefficient() t = F.variables()[0] a = lc.squarefree_part() # lc/a is a square a = lc // a Zx = PolynomialRing(ZZ, 'x') F = Zx(a**(d - 1) * F(t / a)) # Find primes of bad reduction for our model D = F.disc() P = Set(D.prime_divisors()) # Add primes at which Weil bounds do not guarantee a mod p point g = (d - 2) // 2 Weil = [] p = 2 while (p + 1)**2 <= 4 * g**2 * p: Weil.append(p) p = next_prime(p) P = P.union(Set(Weil)) # Test for solubility for p in P: if not IsSolubleAt(F, p): S.append(p) S.sort() return S
def genCurve(bits): p = sg.next_prime(random.randint(2**(bits-1), 2**(bits))) order = 0 while not(sg.is_prime(order)) or order == p or order == p+1: A = random.randint(1, 10**5) B = random.randint(1, 10**5) if (4*A**3 + 27*B**2) % p != 0: ## Avoid singular curves ## E = sg.EllipticCurve(sg.GF(p), [A,B]) order = E.cardinality() P = E.random_point() Q = E.random_point() f = open("curves.csv", "a") f.write(str(bits)+",") f.write(str(A)+",") f.write(str(B)+",") f.write(str(p)+",") f.write(str(order)+",") f.write(str(P.xy()[0])+","+str(P.xy()[1])+",") f.write(str(Q.xy()[0])+","+str(Q.xy()[1])+"\n") f.close()
def genCurve(bits): p = sg.next_prime(random.randint(2**(bits - 1), 2**(bits))) order = 0 while not (sg.is_prime(order)) or order == p or order == p + 1: A = random.randint(1, 10**5) B = random.randint(1, 10**5) if (4 * A**3 + 27 * B**2) % p != 0: ## Avoid singular curves ## E = sg.EllipticCurve(sg.GF(p), [A, B]) order = E.cardinality() P = E.random_point() Q = E.random_point() f = open("curves.csv", "a") f.write(str(bits) + ",") f.write(str(A) + ",") f.write(str(B) + ",") f.write(str(p) + ",") f.write(str(order) + ",") f.write(str(P.xy()[0]) + "," + str(P.xy()[1]) + ",") f.write(str(Q.xy()[0]) + "," + str(Q.xy()[1]) + "\n") f.close()
def central_character_as_artin_rep(self): """ Returns the central character, i.e., determinant character as a web character, but as an Artin representation """ if self.dimension() == 1: return self if 'central_character_as_artin_rep' in self._data: return self._data['central_character_as_artin_rep'] myfunc = self.central_char_function() # Get the Artin field nfgg = self.number_field_galois_group() # Get its artin reps arts = nfgg.ArtinReps() # Filter for 1-dim arts = [a for a in arts if ArtinRepresentation(str(a['Baselabel'])+"c1").dimension()==1] artfull = [ArtinRepresentation(str(a['Baselabel'])+"c"+str(a['GalConj'])) for a in arts] # hold = artfull # Loop as we evaluate at primes until there is only one left # Fix the return value to be what we want artfull = [[a, a.central_char_function(),2*a.character_field()] for a in artfull] n = 2*self.character_field() p = 2 disc = nfgg.discriminant() while len(artfull)>1: if (disc % p) != 0: k=0 while k<len(artfull): if n*artfull[k][1](p,artfull[k][2]) == artfull[k][2]*myfunc(p,n): k += 1 else: # Quick deletion of k-th term artfull[k] = artfull[-1] del artfull[-1] p = next_prime(p) self._data['central_character_as_artin_rep'] = artfull[0][0] return artfull[0][0]
xs.append(1) xs = vector(xs) A = [] for i in range(m): cs = [randrange(hi) for _ in range(n-1)] cs.append(-sum((x*c) for x, c in zip(xs, cs))) assert sum(c*x for c, x in zip(cs, xs)) == 0 A.append(cs) assert xs == small_lgs(matrix(A)) print ' Testing homogenous LGS modulo prime' hi = 2**128 lo = 2**100 p = next_prime(hi) n = 40 # num vars m = 35 # num equations xs = [randrange(lo) for _ in range(n)] xs = vector(xs) A = [] for i in range(m): cs = [randrange(p) for _ in range(n-1)] last_c = -sum(c*x for c, x in zip(cs, xs)) * inverse_mod(xs[-1], p) cs.append(last_c % p) assert sum(c*x for c, x in zip(cs, xs))%p == 0 A.append(cs) A = matrix(ZZ, A)
def render_newform_webpage(label): try: newform = WebNewform.by_label(label) except (KeyError, ValueError) as err: return abort(404, err.args) info = to_dict(request.args) info['format'] = info.get('format', 'embed' if newform.dim > 1 else 'satake') p, maxp = 2, 10 if info['format'] in ['satake', 'satake_angle']: while p <= maxp: if newform.level % p == 0: maxp = next_prime(maxp) p = next_prime(p) errs = [] info['n'] = info.get('n', '2-%s' % maxp) try: info['CC_n'] = integer_options(info['n'], 1000) except (ValueError, TypeError) as err: info['n'] = '2-%s' % maxp info['CC_n'] = range(2, maxp + 1) if err.args and err.args[0] == 'Too many options': errs.append(r"Only \(a_n\) up to %s are available" % (newform.cqexp_prec - 1)) else: errs.append( "<span style='color:black'>n</span> must be an integer, range of integers or comma separated list of integers" ) maxm = min(newform.dim, 20) info['m'] = info.get('m', '1-%s' % maxm) try: info['CC_m'] = integer_options(info['m'], 1000) except (ValueError, TypeError) as err: info['m'] = '1-%s' % maxm info['CC_m'] = range(1, maxm + 1) if err.args and err.args[0] == 'Too many options': errs.append( 'Web interface only supports 1000 embeddings at a time. Use download link to get more (may take some time).' ) else: errs.append( "<span style='color:black'>Embeddings</span> must be an integer, range of integers or comma separated list of integers" ) try: info['prec'] = int(info.get('prec', 6)) if info['prec'] < 1 or info['prec'] > 15: raise ValueError except (ValueError, TypeError): info['prec'] = 6 errs.append( "<span style='color:black'>Precision</span> must be a positive integer, at most 15 (for higher precision, use the download button)" ) newform.setup_cc_data(info) if newform.cqexp_prec != 0 and max(info['CC_n']) >= newform.cqexp_prec: errs.append(r"Only \(a_n\) up to %s are available" % (newform.cqexp_prec - 1)) if errs: flash(Markup("<br>".join(errs)), "error") return render_template("cmf_newform.html", info=info, newform=newform, properties2=newform.properties, downloads=newform.downloads, credit=credit(), bread=newform.bread, learnmore=learnmore_list(), title=newform.title, friends=newform.friends)
def DirichletCoefficients(euler_factors, bound = None): """ INPUT: - ``euler_factors`` -- a dictionary p --> Lp.list() where Lp \in 1 + ZZ[t] OUTPUT: A list of length bound + 1 -- [0, a1, a2, ... , a_bound] EXAMPLES: sage: E17a2_euler_factors = {2: [1, 1, 2], 3: [1, 0, 3], 5: [1, 2, 5], 7: [1, -4, 7], 11: [1, 0, 11], 13: [1, 2, 13], 17: [1, -1], 19: [1, 4, 19], 23: [1, -4, 23], 29: [1, -6, 29], 31: [1, -4, 31], 37: [1, 2, 37], 41: [1, 6, 41], 43: [1, -4, 43], 47: [1, 0, 47], 53: [1, -6, 53], 59: [1, 12, 59], 61: [1, 10, 61], 67: [1, -4, 67], 71: [1, 4, 71], 73: [1, 6, 73], 79: [1, -12, 79], 83: [1, 4, 83], 89: [1, -10, 89], 97: [1, -2, 97]} sage: A = DirichletCoefficients(E17a2_euler_factors, bound = 99) sage: A == [0, 1, -1, 0, -1, -2, 0, 4, 3, -3, 2, 0, 0, -2, -4, 0, -1, 1, 3, -4, 2, 0, 0, 4, 0, -1, 2, 0, -4, 6, 0, 4, -5, 0, -1, -8, 3, -2, 4, 0, -6, -6, 0, 4, 0, 6, -4, 0, 0, 9, 1, 0, 2, 6, 0, 0, 12, 0, -6, -12, 0, -10, -4, -12, 7, 4, 0, 4, -1, 0, 8, -4, -9, -6, 2, 0, 4, 0, 0, 12, 2, 9, 6, -4, 0, -2, -4, 0, 0, 10, -6, -8, -4, 0, 0, 8, 0, 2, -9, 0] True sage: E33a3_euler_factors = {2: [1, -1, 2], 3: [1, 1], 5: [1, 2, 5], 7: [1, -4, 7], 11: [1, -1], 13: [1, 2, 13], 17: [1, 2, 17], 19: [1, 0, 19], 23: [1, -8, 23], 29: [1, 6, 29], 31: [1, 8, 31], 37: [1, -6, 37], 41: [1, 2, 41], 43: [1, 0, 43], 47: [1, -8, 47], 53: [1, -6, 53], 59: [1, 4, 59], 61: [1, -6, 61], 67: [1, 4, 67], 71: [1, 0, 71], 73: [1, 14, 73], 79: [1, 4, 79], 83: [1, -12, 83], 89: [1, 6, 89], 97: [1, -2, 97]} sage: A = DirichletCoefficients(E33a3_euler_factors, bound = 99) sage: A == [0, 1, 1, -1, -1, -2, -1, 4, -3, 1, -2, 1, 1, -2, 4, 2, -1, -2, 1, 0, 2, -4, 1, 8, 3, -1, -2, -1, -4, -6, 2, -8, 5, -1, -2, -8, -1, 6, 0, 2, 6, -2, -4, 0, -1, -2, 8, 8, 1, 9, -1, 2, 2, 6, -1, -2, -12, 0, -6, -4, -2, 6, -8, 4, 7, 4, -1, -4, 2, -8, -8, 0, -3, -14, 6, 1, 0, 4, 2, -4, 2, 1, -2, 12, 4, 4, 0, 6, -3, -6, -2, -8, -8, 8, 8, 0, -5, 2, 9, 1] True """ if bound is None: bound = next_prime( max(euler_factors.keys() ) ) - 1; degree = 0; for p, L in euler_factors.iteritems(): if len(L) > degree + 1: degree = len(L) - 1; R = PolynomialRing(ZZ, degree, "a") S = PowerSeriesRing(R, default_prec = ceil(log(bound)/log(2))); P = [1] + list(R.gens()); recursion = (1/S(P)).list(); A = [None]*(bound + 1); A[0] = 0; A[1] = 1; i = 1; # sieve through [1, bound] while i <= bound: if A[i] is None: #i is a prime if i in euler_factors: euler_i = euler_factors[i][1:]; else: euler_i = []; euler_i += [0] * (degree - len(euler_i)); # fill with zeros if necessary # deal with its powers r = 1; ipower = i # i^r while ipower <= bound: A[ipower] = recursion[r](euler_i) ipower *= i; r += 1; # deal with multiples of its powers by smaller numbers for m in range(2, bound): if A[m] is not None and m%i != 0: ipower = i while m*ipower <= bound: assert A[m*ipower] is None A[m*ipower] = A[m] * A[ipower] ipower *= i i += 1 return A;
def _compute_simple_modules_graph_from_startpoint(self, s, p=None, cut_nonsimple_aniso=True, fast=1): # for forking this is necessary logger = get_logger(s) # print logger k = self._weight ########################################################### # Determine which primes need to be checked # According to the proof of Proposition XX in [BEF], we # only need to check primesnot dividing the 6*level(s), # for which prime_pol(s,p,k) <= 0. # For those primes, we check if there is any # k-simple fqm in s.C(p) and if not, we do not have to # consider p anymore. ########################################################### if p == None: p = 2 N = Integer(6) * s.level() slp = N.prime_factors() for q in prime_range(next_prime(N) + 1): if not q in slp: logger.info( "Smallest prime not dividing 6*level({0}) = {1} is p = {2}".format(s, Integer(6) * s.level(), q)) p = q break while prime_pol(s, p, k) <= 0 or p in slp: p = next_prime(p) p = uniq(prime_range(p) + slp) logger.info("Starting with s = {0} and primes = {1}".format(s, p)) if isinstance(p, list): primes = p else: primes = [p] simple = s.is_simple(k, reduction = self._reduction, bound = self._bound) if not simple: logger.info("{0} is not simple.".format(s)) # print simple s = FQM_vertex(s) # print s self.add_vertex(s) # print "added vertex ", s ############################################################ # Starting from the list of primes we generated, # we now compute which primes we actually need to consider. # That is, the primes such that there is a fqm in s.C(p) # which is k-simple. ############################################################ np = list() if cut_nonsimple_aniso and simple: for i in range(len(primes)): p = primes[i] fs = False for t in s.genus_symbol().C(p, False): if t.is_simple(k, bound = self._bound): fs = True logger.debug("Setting fs = True") break if fs: np.append(p) primes = np # print "here", primes logger.info("primes for graph for {0}: {1}".format(s, primes)) # if len(primes) == 0: # return heights = self._heights h = 0 if not heights.has_key(h): heights[h] = [s] else: if heights[h].count(s) == 0: heights[h].append(s) vertex_colors = self._vertex_colors nonsimple_color = self._nonsimple_color simple_color = self._simple_color # Bs contains the modules of the current level (= height = h) Bs = [s] # set the correct color for the vertex s if simple: if vertex_colors[simple_color].count(s) == 0: vertex_colors[simple_color].append(s) elif vertex_colors[nonsimple_color].count(s) == 0: vertex_colors[nonsimple_color].append(s) ################################################### # MAIN LOOP # we loop until we haven't found any simple fqm's ################################################### while simple: h = h + 1 if not heights.has_key(h): heights[h] = list() # the list Bss will contain the k-simple modules of the next height level # recall that Bs contains the modules of the current height level Bss = list() simple = False # checklist = modules that we need to check for with .is_simple(k) # we assemble this list because afterwards # we check them in parallel checklist = [] for s1 in Bs: Bs2 = list() for p in primes: # check if we really need to check p for s1 # otherwise none of the fqm's in s1.C(p) are simple # and we will not consider them. if prime_pol(s1.genus_symbol(), p, k) <= 0: Bs2 = Bs2 + s1.genus_symbol().C(p, False) else: logger.info( "Skipping p = {0} for s1 = {1}".format(p, s1)) # print "Skipping p = {0} for s1 = {1}".format(p, s1) # print "Bs2 = ", Bs2 # now we actually check the symbols in Bs2 for s2 in Bs2: if s2.max_rank() > self._rank_limit: # we skip s2 if its minimal number of generators # is > than the given rank_limit. continue s2 = FQM_vertex(s2) skip = False for v in self._heights[h]: # we skip symbols that correspond to isomorphic modules if v.genus_symbol().defines_isomorphic_module(s2.genus_symbol()): skip = True logger.debug( "skipping {0} b/c isomorphic to {1}".format(s2.genus_symbol(), v.genus_symbol())) s2 = v break if skip: continue if not skip: self.add_vertex(s2) heights[h].append(s2) self.update_edges(s2, h, fast=fast) # before using the actual dimension formula # we check if there is already a non-k-simple neighbor # (an incoming edge from a non-k-simple module) # which would imply that s2 is not k-simple. has_nonsimple_neighbor = False for e in self.incoming_edges(s2): if vertex_colors[nonsimple_color].count(e[0]) > 0: has_nonsimple_neighbor = True logger.debug( "Has nonsimple neighbor: {0}".format(s2.genus_symbol())) break if has_nonsimple_neighbor: #not simple if not vertex_colors[nonsimple_color].count(s2) > 0: vertex_colors[nonsimple_color].append(s2) else: checklist.append((s2, k, self._reduction, self._bound)) logger.debug("checklist = {0}".format(checklist)) # check the modules in checklist # for being k-simple # this is done in parallel # when a process returns # we add the vertex and give it its appropriate color if NCPUS1 == 1: checks = [([[s[0]]],check_simple(*s)) for s in checklist] else: checks = list(check_simple(checklist)) logger.info("checks = {0}".format(checks)) for check in checks: s2 = check[0][0][0] if check[1]: simple = True logger.info( "Found simple module: {0}".format(s2.genus_symbol())) Bss.append(s2) if not vertex_colors[simple_color].count(s2) > 0: vertex_colors[simple_color].append(s2) else: if not vertex_colors[nonsimple_color].count(s2) > 0: vertex_colors[nonsimple_color].append(s2) Bs = Bss simple = [v.genus_symbol() for v in vertex_colors[simple_color]] self._simple = uniq(simple)
Z = [0,]*len(X) for i in range(len(X)): x = X[i] z = previous_prime(x) # Returns z < x if is_prime(x): # galois.prev_prime() returns z <= x z = x Z[i] = int(z) d = {"X": X, "Z": Z} save_pickle(d, FOLDER, "prev_prime.pkl") set_seed(SEED + 304) X = [random.randint(1, 100) for _ in range(20)] + [random.randint(100, 1_000_000) for _ in range(20)] Z = [0,]*len(X) for i in range(len(X)): x = X[i] z = next_prime(x) Z[i] = int(z) d = {"X": X, "Z": Z} save_pickle(d, FOLDER, "next_prime.pkl") set_seed(SEED + 305) X = [random.randint(-100, 100) for _ in range(20)] + [random.randint(100, 1_000_000_000) for _ in range(20)] Z = [0,]*len(X) for i in range(len(X)): x = X[i] z = is_prime(x) Z[i] = bool(z) d = {"X": X, "Z": Z} save_pickle(d, FOLDER, "is_prime.pkl") # set_seed(SEED + 306)
def _compute_simple_modules_graph_from_startpoint(self, s, p=None, cut_nonsimple_aniso=True, fast=1): # for forking this is necessary logger = get_logger(s) # print logger k = self._weight ########################################################### # Determine which primes need to be checked # According to the proof of Proposition XX in [BEF], we # only need to check primesnot dividing the 6*level(s), # for which prime_pol(s,p,k) <= 0. # For those primes, we check if there is any # k-simple fqm in s.C(p) and if not, we do not have to # consider p anymore. ########################################################### if p == None: p = 2 N = Integer(6) * s.level() slp = N.prime_factors() for q in prime_range(next_prime(N) + 1): if not q in slp: logger.info( "Smallest prime not dividing 6*level({0}) = {1} is p = {2}" .format(s, Integer(6) * s.level(), q)) p = q break while prime_pol(s, p, k) <= 0 or p in slp: p = next_prime(p) p = uniq(prime_range(p) + slp) logger.info("Starting with s = {0} and primes = {1}".format(s, p)) if isinstance(p, list): primes = p else: primes = [p] simple = s.is_simple(k, reduction=self._reduction, bound=self._bound) if not simple: logger.info("{0} is not simple.".format(s)) # print simple s = FQM_vertex(s) # print s self.add_vertex(s) # print "added vertex ", s ############################################################ # Starting from the list of primes we generated, # we now compute which primes we actually need to consider. # That is, the primes such that there is a fqm in s.C(p) # which is k-simple. ############################################################ np = list() if cut_nonsimple_aniso and simple: for i in range(len(primes)): p = primes[i] fs = False for t in s.genus_symbol().C(p, False): if t.is_simple(k, bound=self._bound): fs = True logger.debug("Setting fs = True") break if fs: np.append(p) primes = np # print "here", primes logger.info("primes for graph for {0}: {1}".format(s, primes)) # if len(primes) == 0: # return heights = self._heights h = 0 if not heights.has_key(h): heights[h] = [s] else: if heights[h].count(s) == 0: heights[h].append(s) vertex_colors = self._vertex_colors nonsimple_color = self._nonsimple_color simple_color = self._simple_color # Bs contains the modules of the current level (= height = h) Bs = [s] # set the correct color for the vertex s if simple: if vertex_colors[simple_color].count(s) == 0: vertex_colors[simple_color].append(s) elif vertex_colors[nonsimple_color].count(s) == 0: vertex_colors[nonsimple_color].append(s) ################################################### # MAIN LOOP # we loop until we haven't found any simple fqm's ################################################### while simple: h = h + 1 if not heights.has_key(h): heights[h] = list() # the list Bss will contain the k-simple modules of the next height level # recall that Bs contains the modules of the current height level Bss = list() simple = False # checklist = modules that we need to check for with .is_simple(k) # we assemble this list because afterwards # we check them in parallel checklist = [] for s1 in Bs: Bs2 = list() for p in primes: # check if we really need to check p for s1 # otherwise none of the fqm's in s1.C(p) are simple # and we will not consider them. if prime_pol(s1.genus_symbol(), p, k) <= 0: Bs2 = Bs2 + s1.genus_symbol().C(p, False) else: logger.info("Skipping p = {0} for s1 = {1}".format( p, s1)) # print "Skipping p = {0} for s1 = {1}".format(p, s1) # print "Bs2 = ", Bs2 # now we actually check the symbols in Bs2 for s2 in Bs2: if s2.max_rank() > self._rank_limit: # we skip s2 if its minimal number of generators # is > than the given rank_limit. continue s2 = FQM_vertex(s2) skip = False for v in self._heights[h]: # we skip symbols that correspond to isomorphic modules if v.genus_symbol().defines_isomorphic_module( s2.genus_symbol()): skip = True logger.debug( "skipping {0} b/c isomorphic to {1}".format( s2.genus_symbol(), v.genus_symbol())) s2 = v break if skip: continue if not skip: self.add_vertex(s2) heights[h].append(s2) self.update_edges(s2, h, fast=fast) # before using the actual dimension formula # we check if there is already a non-k-simple neighbor # (an incoming edge from a non-k-simple module) # which would imply that s2 is not k-simple. has_nonsimple_neighbor = False for e in self.incoming_edges(s2): if vertex_colors[nonsimple_color].count(e[0]) > 0: has_nonsimple_neighbor = True logger.debug("Has nonsimple neighbor: {0}".format( s2.genus_symbol())) break if has_nonsimple_neighbor: #not simple if not vertex_colors[nonsimple_color].count(s2) > 0: vertex_colors[nonsimple_color].append(s2) else: checklist.append((s2, k, self._reduction, self._bound)) logger.debug("checklist = {0}".format(checklist)) # check the modules in checklist # for being k-simple # this is done in parallel # when a process returns # we add the vertex and give it its appropriate color if NCPUS1 == 1: checks = [([[s[0]]], check_simple(*s)) for s in checklist] else: checks = list(check_simple(checklist)) logger.info("checks = {0}".format(checks)) for check in checks: s2 = check[0][0][0] if check[1]: simple = True logger.info("Found simple module: {0}".format( s2.genus_symbol())) Bss.append(s2) if not vertex_colors[simple_color].count(s2) > 0: vertex_colors[simple_color].append(s2) else: if not vertex_colors[nonsimple_color].count(s2) > 0: vertex_colors[nonsimple_color].append(s2) Bs = Bss simple = [v.genus_symbol() for v in vertex_colors[simple_color]] self._simple = uniq(simple)
def get_type_1_primes(K, aux_prime_count=3, loop_curves=False): """Compute the type 1 primes""" C_K = K.class_group() aux_primes = [Q_2] prime_to_append = Q_2 for _ in range(1, aux_prime_count): prime_to_append = next_prime(prime_to_append) aux_primes.append(prime_to_append) # We need at least one aux prime that splits to have provable termination my_legendre_symbols = set([legendre_symbol(K._D, p) for p in aux_primes]) if 1 not in my_legendre_symbols: prime_to_append = next_prime(prime_to_append) while legendre_symbol(K._D, prime_to_append) != 1: prime_to_append = next_prime(prime_to_append) aux_primes.append(prime_to_append) D_dict = {} for q in aux_primes: frak_q = K.primes_above(q)[0] residue_field = frak_q.residue_field(names="z") residue_field_card = residue_field.cardinality() frak_q_class_group_order = C_K(frak_q).multiplicative_order() exponent = 12 * frak_q_class_group_order running_D = q if loop_curves: weil_polys = get_weil_polys(residue_field) else: weil_polys = R.weil_polynomials(2, residue_field_card) # First add the C((0,0), frak_q) terms for wp in weil_polys: D = get_C00(wp, residue_field_card, exponent) D = Integer(D) # If q splits then we know C((0,0),frak_q) is non-zero # so we can insist on only adding D if it is non-zero if legendre_symbol(K._D, q) == 1: if D != 0: running_D = lcm(running_D, D) else: # Here we do not provably know that the integer is non-zero # so add it directly to the running_D running_D = lcm(running_D, D) # Put the other term in the lcm before adding to dictionary running_D = lcm(residue_field_card ** exponent - 1, running_D) D_dict[q] = running_D output = gcd(list(D_dict.values())) output = set(output.prime_divisors()) # Add the bad formal immersion primes output = output.union(set(prime_range(62)), {71}) # Sort and return output = list(output) output.sort() return output
import sys from random_curve_iterator import RandomCurveIterator from sage.all import GF, next_prime if __name__ == "__main__": p = next_prime(100) F = GF(p) count = 0 for ec in RandomCurveIterator(F): if ec.cardinality() == p - 1: print(ec) sys.exit()
nfcc = [int(z.order()) for z in nfcc] nfcc = lcm(nfcc) if not cfz.divides(nfcc): print("Failure " + str(cfz) + " divides " + str(nfcc) + " from " + label) sys.exit() R, x = QQ['x'].objgen() pol1 = R.cyclotomic_polynomial(nfcc) K, z = NumberField(R.cyclotomic_polynomial(nfcc), 'z').objgen() RR, y = K['y'].objgen() zsmall = z**(nfcc / cfz) allpols = [ sum(y**k * sum(pp[k][j] * zsmall**j for j in range(len(pp[k]))) for k in range(len(pp))) for pp in ar.local_factors_table() ] allroots = [myroots(pp, nfcc, z) for pp in allpols] outfile.write(str(nfcc) + "\n") outfile.write(str(allroots) + "\n") j = 0 p = 1 while j < bound: p = next_prime(p) outfile.write(str(ar.any_prime_to_cc_index(p)) + "\n") j += 1 #plist = [ar.any_prime_to_cc_index(p) for p in primes_first_n(bound)] #for j in plist: # outfile.write(str(j)+"\n") outfile.close()
cfz = ZZ(cf) nf = ar.nf() nfcc = nf.conjugacy_classes() nfcc = [int(z.order()) for z in nfcc] nfcc = lcm(nfcc) if not cfz.divides(nfcc): print "Failure "+str(cfz)+" divides "+str(nfcc)+" from "+label sys.exit() R,x = QQ['x'].objgen() pol1 = R.cyclotomic_polynomial(nfcc) K,z=NumberField(R.cyclotomic_polynomial(nfcc),'z').objgen() RR,y = K['y'].objgen() zsmall = z**(nfcc/cfz) allpols = [sum(y**k * sum(pp[k][j] * zsmall**j for j in range(len(pp[k]))) for k in range(len(pp))) for pp in ar.local_factors_table()] allroots = [myroots(pp, nfcc, z) for pp in allpols] outfile.write(str(nfcc)+"\n") outfile.write(str(allroots)+"\n") j=0 p=1 while j<bound: p = next_prime(p) outfile.write(str(ar.any_prime_to_cc_index(p))+"\n") j+=1 #plist = [ar.any_prime_to_cc_index(p) for p in primes_first_n(bound)] #for j in plist: # outfile.write(str(j)+"\n") outfile.close()