예제 #1
0
def _dimension_Kp(wt, p):
    """
    Return the dimensions of subspaces of Siegel modular forms on $K(p)$
    for primes $p$.

    OUTPUT
        ("Total", "Gritsenko Lifts", "Nonlifts", "Oldforms")
    """
    oldforms = 0
    grits = __JacobiDimension(wt, p)

    if not is_prime(p):
        return (uk, grits, uk, uk)

    if wt <= 1:
        return (0, 0, 0, 0)
    if wt == 2:
        newforms = '?'
        total = '' + str(grits) + ' - ?'
        if p < 600:
            newforms = 0
            total = grits
            interestingPrimes = [277, 349, 353, 389, 461, 523, 587]
            if p in interestingPrimes:
                if p == 587:
                    newforms = '0 - 2'
                    total = '' + str(grits) + ' - ' + str(grits + 2)
                newforms = '0 - 1'
                total = '' + str(grits) + ' - ' + str(grits + 1)
        return (total, grits, newforms, oldforms)

    total = dimKp(wt, p)
    newforms = total - grits - oldforms
    return (total, grits, newforms, oldforms)
예제 #2
0
    def t2(self, q=3):
        """
        Return mod 2 matrix t2 computed using the current choice of
        prime q, as returned by self.q.
        
        INPUT:
        
            - `q` -- integer


        OUTPUT:

            - a mod 2 matrix

        EXAMPLES::

            sage: from mdsage import *
            sage: C = KamiennyCriterion(29)
            sage: C.t2()[0]
            (1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0)
        """
        if q==2 or self.p % q == 0 or not is_prime(q):
            raise ValueError("q must be prime, unequal to 2 and not divide self.p")
        if self.congruence_type==0:
            return self.T(q) - (q  + 1)
        else:
            return self.T(q) -  self.dbd(q) - q
예제 #3
0
파일: Bsets.py 프로젝트: s-opitz/sfqm
def prime_anisotropic_symbols(p):
    print p
    if not (p==1 or is_prime(p) or p == 4 or p == 8):
        raise ValueError
    else:
        if is_odd(p) and is_prime(p):
            if p % 4 == 3:
                return [str(p) + '^+1', str(p) + '^-1', str(p) + '^+2']
            else:
                return [str(p) + '^+1', str(p) + '^-1', str(p) + '^-2']
        else:
            if p==1:
                return ['']
            if p == 2:
                return ['2^-2']
            elif p==4:
                return ['2_1^+1', '2_7^+1', '2_2^+2', '2_0^+2', '2_3^-3', '2_5^-3']
            elif p==8:
                return ['4_1^+1', '4_3^-1', '4_5^-1', '4_7^+1', '2_1^+1.4_1^+1', '2_1^+1.4_3^-1', '2_1^+1.4_5^-1', '2_1^+1.4_7^+1']
예제 #4
0
 def _set_coset_reps(self):
     if is_prime(self._level):
         self._coset_reps[0] = SL2Z([1,0,0,1])
         for n in range(self._level):
             self._coset_reps[n+1] = SL2Z([0,-1,1,n])
     else:
         G = Gamma0(self._level)
         n = 0
         for A in G.coset_reps():
             self._coset_reps[n] = A
             n+=1
예제 #5
0
def is_valid_curve(q,t,r,k,D): 
    """
    Description:
    
        Tests that (q,t,r,k,D) is a valid elliptic curve
    
    Input:
    
        q - size of prime field
        t - trace of Frobenius
        r - size of prime order subgroup
        k - embedding degree
        D - (negative) fundamental discriminant
    
    Output:
    
        bool - true iff there exists an elliptic curve over F_q with trace t, a subgroup of order r with embedding degree k, and fundamental discriminant D
    
    """
    if q == 0 or t == 0 or r == 0 or k == 0 or D == 0:
        return False
    if not is_prime(q):
        return False 
    if not is_prime(r):
        return False
    if not fundamental_discriminant(D) == D:
        return False
    if D % 4 == 0: #check CM equation
        if not is_square(4*(t*t - 4*q)//D):
            return False
    if D % 4 == 1:
        if not is_square((t*t - 4*q)//D):
            return False
    if not (q+1-t) % r == 0: #check r | #E(F_q)
        return False
    if not power_mod(q,k,r) == 1: #check embedding degree is k
        return False
    return True
예제 #6
0
def _mnt_subcall(k,D, m, condition, modulus, c1, c2, l1, l2, t1, t2, q0):
    D2 = -3*D
    D2 = Integer(D2)
    assert condition(-D), 'No curve exists'
    pell_sols = pell_solve(D2, m) # solve the Pell equation
    curves = []
    curves2 = []
    if len(pell_sols[1])== 0: # no solutions found, so abort
        return curves
    sols = [(Integer(i[0]), Integer(i[1])) for i in pell_sols[1]]
    gen = (Integer(pell_sols[0][0]), Integer(pell_sols[0][1]))
    q = 0
    t = 0
    for i in range(0, len(sols)):
        if sols[i][0] < 0:
            sols[i] = (sols[i][0]*gen[0] + D2*sols[i][1]*gen[1], sols[i][1]*gen[0] + sols[i][0]*gen[1])
    for sol in sols:
        check = False
        x = sol[0]
        l = 0
        t = 0
        q = 0
        if x % modulus == c1:
            l = l1(x)
            t = t1(l)
            check = True
        elif x % modulus == c2:
            l = l2(x)
            t = t2(l)
            check = True
        if check:
            q = q0(l)
            if is_prime(q) and is_prime(q+1-t):
                if ((q,t) not in curves2):
                    curves.append((q,t,q+1-t,k,D))
                    curves2.append((q,t)) 
    return curves
예제 #7
0
def is_suitable_q(q):
    """
    Description:
    
        User-defined method that filters the set of primes q that are returned. By default checks if q is prime
    
    Input:
    
        q - integer
    
    Output:
    
        bool - true iff q is suitable
    
    """
    return is_prime(q)
예제 #8
0
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()
예제 #9
0
def test_ec(num_tests,num_bits, debug=False):
    print('testing EC chain...')
    func_start = time.time()
    fail = 0
    for i in range(0, num_tests):
        try:
            k = randint(5,20)
            r = 0
            while not (r % k == 1 and is_prime(r)):
                r = random_prime(2**(num_bits-1), 2**num_bits)
            k_vector = [k]
            k_vector.append(randint(5,20))
            k_vector.append(randint(5,20))
            curves = ec.new_chain(r, k_vector)
            assert ec.is_chain(curves)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
예제 #10
0
파일: plots.py 프로젝트: defeo/ffisom
def primes_arith_prog(bound=10**4, out='arith_prog.pdf', d=3):
    '''
    Run through all prime powers r up to `bound`, and select for each
    the smallest u such that ur+1 is prime.
    
    Then do degree `d` linear regression, and plot everything into 
    `out`.
    '''
    # Find primes
    x, y = np.array([(p, next(u for u in xrange(p) if is_prime(u*p+1)))
                     for p in prime_powers(3,bound)]).T
    # linear regression
    lstsq = np.polyfit(np.log10(x), y, d)

    # Figure settings
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif', serif='Computer Modern')
    plt.figure(figsize=(8,3))

    # Plot a 2D histogram of the data, with abscissa in log scale
    plt.hist2d(np.log10(x), y, bins=(1.5*max(y),max(y)/2),
               weights=np.log10(x)/x,
               cmap=cm.jet, norm=LogNorm())
    plt.colorbar()
    # Plot the linear regression
    x = np.linspace(*plt.xlim(), num=100)
    plt.plot(x, np.polyval(lstsq, x), c='black', label='degree %d polynomial regression' % d)
    plt.legend(loc='upper left')

    # More figure settings
    locs, _ = plt.xticks()
    plt.xticks(locs, map(lambda l: '$10^%d$' % l, locs))
    plt.tight_layout()
    # Write to file
    plt.savefig(out, bbox_inches='tight')
    plt.close()
예제 #11
0
    def general_webpagedata(self):
        info = {}
        try:
            info['support'] = self.support
        except AttributeError:
            info['support'] = ''

        info['Ltype'] = self.Ltype()

        try:
            info['label'] = self.label
        except AttributeError:
            info['label'] = ""

        try:
            info['credit'] = self.credit
        except AttributeError:
            info['credit'] = ""

        info['degree'] = int(self.degree)
        info['conductor'] = self.level
        if not is_prime(int(self.level)):
            if self.level >= 10**8:
                info['conductor'] = latex(self.level_factored)
            else:
                info['conductor_factored'] = latex(self.level_factored)


        info['sign'] = "$" + styleTheSign(self.sign) + "$"
        info['algebraic'] = self.algebraic
        if self.selfdual:
            info['selfdual'] = 'yes'
        else:
            info['selfdual'] = 'no'
        if self.primitive:
            info['primitive'] = 'yes'
        else:
            info['primitive'] = 'no'
        info['dirichlet'] = lfuncDShtml(self, "analytic")
        # Hack, fix this more general?
        info['dirichlet'] = info['dirichlet'].replace('*I','<em>i</em>')

        info['eulerproduct'] = lfuncEPtex(self, "abstract")
        info['functionalequation'] = lfuncFEtex(self, "analytic")
        info['functionalequationSelberg'] = lfuncFEtex(self, "selberg")

        if hasattr(self, 'positive_zeros'):
            info['positive_zeros'] = self.positive_zeros
            info['negative_zeros'] = self.negative_zeros

        if hasattr(self, 'plot'):
            info['plot'] = self.plot

        if hasattr(self, 'factorization'):
            info['factorization'] = self.factorization

        if self.fromDB and self.algebraic:
            info['dirichlet_arithmetic'] = lfuncDShtml(self, "arithmetic")
            info['eulerproduct_arithmetic'] = lfuncEPtex(self, "arithmetic")
            info['functionalequation_arithmetic'] = lfuncFEtex(self, "arithmetic")

            if self.motivic_weight % 2 == 0:
               arith_center = "\\frac{" + str(1 + self.motivic_weight) + "}{2}"
            else:
               arith_center = str(ZZ(1)/2 + self.motivic_weight/2)
            svt_crit = specialValueTriple(self, 0.5, '\\frac12',arith_center)
            info['sv_critical'] = svt_crit[0] + "\\ =\\ " + svt_crit[2]
            info['sv_critical_analytic'] = [svt_crit[0], svt_crit[2]]
            info['sv_critical_arithmetic'] = [svt_crit[1], svt_crit[2]]

            if self.motivic_weight % 2 == 1:
               arith_edge = "\\frac{" + str(2 + self.motivic_weight) + "}{2}"
            else:
               arith_edge = str(ZZ(1) + self.motivic_weight/2)

            svt_edge = specialValueTriple(self, 1, '1',arith_edge)
            info['sv_edge'] = svt_edge[0] + "\\ =\\ " + svt_edge[2]
            info['sv_edge_analytic'] = [svt_edge[0], svt_edge[2]]
            info['sv_edge_arithmetic'] = [svt_edge[1], svt_edge[2]]

            chilatex = "$\chi_{" + str(self.charactermodulus) + "} (" + str(self.characternumber) +", \cdot )$"
            info['chi'] = ''
            if self.charactermodulus != self.level:
                info['chi'] += "induced by "
            info['chi'] += '<a href="' + url_for('characters.render_Dirichletwebpage', 
                                                    modulus=self.charactermodulus, number=self.characternumber)
            info['chi'] += '">' + chilatex + '</a>'

            info['st_group'] = self.st_group
            info['st_link'] = self.st_link
            info['rank'] = self.order_of_vanishing
            info['motivic_weight'] = r'\(%d\)' % self.motivic_weight

        elif self.Ltype() == "riemann":
            info['sv_edge'] = r"\[\zeta(1) \approx $\infty$\]"
            info['sv_critical'] = r"\[\zeta(1/2) \approx -1.460354508\]"

        elif self.Ltype() != "artin" or (self.Ltype() == "artin" and self.sign != 0):
            try:
                info['sv_edge'] = specialValueString(self, 1, '1')
                info['sv_critical'] = specialValueString(self, 0.5, '1/2')
            except:
                info['sv_critical'] = "L(1/2): not computed"
                info['sv_edge'] = "L(1): not computed"

        return info
예제 #12
0
 def primes(self, primes, test=True):
     self._primes = primes
     if test:
         for p in primes:
             if not is_prime(p):
                 self._primes.remove(p)
예제 #13
0
파일: test_rsa.py 프로젝트: hellman/cry
def test_SECCON_2020_crypto01():
    masked_flag = 8077275413285507538357977814283814136815067070436948406142717872478737670143034266458000767181162602217137657160614964831459653429727469965712631294123225
    ciphertexts = [
        (
            886775008733978973740257525650074677865489026053222554158847150065839924739525729402395428639350660027796013999414358689067171124475540042281892825140355436902197270317502862419355737833115120643020255177020178331283541002427279377648285229476212651491301857891044943211950307475969543789857568915505152189,
            428559018841948586040450870835405618958247103990365896475476359721456520823105336402250177610460462882418373365551361955769011150860740050608377302711322189733933012507453380208960247649622047461113987220437673085,
            (80103920082434941308951713928956232093682985133090231319482222058601362901404235742975739345738195056858602864819514638254604213654261535503537998613664606957411824998071339098079622119781772477940471338367084695408560473046701072890754255641388442248683562485936267601216704036749070688609079527182189924,
             842529568002033827493313169405480104392127700904794758022297608679141466431472390397211660887148306350328312067659313538964875094877785244888004725864621826211254824064492961341512012172365417791553455922872091302295614295785447354268009914265614957287377743897340475899980395298019735631787570231395791009
             ),
            59051335744243522933765175665,
        ),
        (
            37244493713246153778174562251362609960152354778990433088693945121840521598316370898923829767722653817418453309557995775960963654893571162621888675965423771020678918714406461976659339420718804301006282789714856197345257634581330970033427061846386874027391337895557558939538516456076874074642348992933600929747,
            152657520846237173082171645969128953029734435220247551748055538422696193261367413610113664730705318574898280226247526051526753570012356026049784218573767765351341949785570284026342156807244268439356037529507501666987,
            (14301224815357080657295611483943004076662022528706782110580690613822599700117720290144067866898573981166927919045773324162651193822888938569692341428439887892150361361566562459037438581637126808773605536449091609307652818862273375400935935851849153633881318435727224452416837785155763820052159016539063161774,
             711567521767597846126014317418558888899966530302382481896965868976010995445213619798358362850235642988939870722858624888544954189591439381230859036120045216842190726357421800117080884618285875510251442474167884705409694074544449959388473647082485564659040849556130494057742499029963072560315800049629531101
             ),
            56178670950277431873900982569,
        ),
        (
            6331516792334912993168705942035497262087604457828016897033541606942408964421467661323530702416001851055818803331278149668787143629857676822265398153269496232656278975610802921303671791426728632525217213666490425139054750899596417296214549901614709644307007461708968510489409278966392105040423902797155302293,
            2041454339352622193656627164408774503102680941657965640324880658919242765901541504713444825283928928662755298871656269360429687747026596290805541345773049732439830112665647963627438433525577186905830365395002284129,
            (4957181230366693742871089608567285130576943723414681430592899115510633732100117146460557849481224254840925101767808247789524040371495334272723624632991086495766920694854539353934108291010560628236400352109307607758762704896162926316651462302829906095279281186440520100069819712951163378589378112311816255944,
             2715356151156550887523953822376791368905549782137733960800063674240100539578667744855739741955125966795181973779300950371154326834354436541128751075733334790425302253483346802547763927140263874521376312837536602237535819978061120675338002761853910905172273772708894687214799261210445915799607932569795429868
             ),
            70953285682097151767648136059,
        ),
    ]
    HINTSIZE = 96

    def decrypt(c, d, n):
        n = int(n)
        size = n.bit_length() // 2
        c_high, c_low = c
        b = (c_low**2 - c_high**3) % n
        EC = EllipticCurve(Zmod(n), [0, b])
        m_high, m_low = (EC((c_high, c_low)) * d).xy()
        m_high, m_low = int(m_high), int(m_low)
        return (m_high << size) | m_low

    hintmod = 2**HINTSIZE
    todec = masked_flag
    for data in ciphertexts:
        n, e, c, hint = data
        c_high, c_low = c
        for f in (e / QQ(n)).continued_fraction().convergents():
            y = f.numerator()
            x = f.denominator()
            if is_prime(x) and is_prime(y):
                print("good", x, y)
                break

        plo = hint
        qlo = n * inverse_mod(plo, hintmod) % hintmod
        slo = (plo + qlo) % hintmod
        assert plo * qlo % hintmod == n % hintmod

        a = e * x - (n + 1) * y

        z_mod_y = (-a) % y
        z_mod_hintmod = (-a + slo * y) % hintmod
        midmod = hintmod * y
        zmid = crt([z_mod_y, z_mod_hintmod], [y, hintmod])

        aa = a - slo * y + zmid
        assert aa % midmod == 0
        aa //= midmod

        # shi = (p + q) // hintmod
        # zhi is ~216 bits
        # assert shi == aa + zhi

        sumpq = aa * hintmod
        eps = 2**216 * hintmod

        rsa = RSA(n)
        pbound, qbound = rsa.bound_primes_from_approximate_sum(
            sumpq - eps, 2 * eps)

        try:
            print("factor1")
            p, q = rsa.factor_with_prime_hint(low_mod=(plo, hintmod),
                                              bounds=pbound,
                                              beta=0.49)
        except RuntimeError:
            print("factor2")
            p, q = rsa.factor_with_prime_hint(low_mod=(qlo, hintmod),
                                              bounds=pbound,
                                              beta=0.49)
        print("ok!")
        d = inverse_mod(e, n + p + q + 1)
        mask = decrypt(c, d, n)
        todec ^= mask
    assert Bin(todec).bytes == b'SECCON{gut_poweeeeeeeeeeeeeer}'
예제 #14
0
    Z[i] = bool(z)
d = {"X": X, "Z": Z}
save_pickle(d, FOLDER, "is_cyclic.pkl")


###############################################################################
# Prime number functions
###############################################################################

set_seed(SEED + 301)
X = [random.randint(1, 1000) for _ in range(10)]
Z = [0,]*len(X)
for i in range(len(X)):
    x = X[i]
    z = prime_range(x)  # Returns primes 0 <= p < x
    if is_prime(x):  # galois.primes() returns 0 <= p <= x
        z.append(x)
    Z[i] = [int(zz) for zz in z]
d = {"X": X, "Z": Z}
save_pickle(d, FOLDER, "primes.pkl")

set_seed(SEED + 302)
X = [random.randint(1, 1000) for _ in range(20)]
Z = [0,]*len(X)
for i in range(len(X)):
    x = X[i]
    z = nth_prime(x)
    Z[i] = int(z)
d = {"X": X, "Z": Z}
save_pickle(d, FOLDER, "kth_prime.pkl")
예제 #15
0
def lfuncFEtex(L, fmt):
    """
    Return the LaTex for displaying the Functional equation of the L-function L.
    fmt could be any of the values: "analytic", "selberg"
    """
    if fmt == "arithmetic":
        mu_list = [mu - L.motivic_weight / 2 for mu in L.mu_fe]
        nu_list = [nu - L.motivic_weight / 2 for nu in L.nu_fe]
        mu_list.sort()
        nu_list.sort()
        texname = L.texname_arithmetic
        try:
            tex_name_s = L.texnamecompleteds_arithmetic
            tex_name_1ms = L.texnamecompleted1ms_arithmetic
        except AttributeError:
            tex_name_s = L.texnamecompleteds
            tex_name_1ms = L.texnamecompleted1ms

    else:
        mu_list = L.mu_fe[:]
        nu_list = L.nu_fe[:]
        texname = L.texname
        tex_name_s = L.texnamecompleteds
        tex_name_1ms = L.texnamecompleted1ms
    ans = ""
    if fmt == "arithmetic" or fmt == "analytic":
        ans = r"\begin{aligned}" + tex_name_s + r"=\mathstrut &"
        if L.level > 1:
            if L.level >= 10**8 and not is_prime(int(L.level)):
                ans += r"\left(%s\right)^{s/2}" % latex(L.level_factored)
            else:
                ans += latex(L.level) + "^{s/2}"
            ans += r" \, "

        def munu_str(factors_list, field):
            assert field in [r"\R", r"\C"]
            # set up to accommodate multiplicity of Gamma factors
            old = ""
            res = ""
            curr_exp = 0
            for elt in factors_list:
                if elt == old:
                    curr_exp += 1
                else:
                    old = elt
                    if curr_exp > 1:
                        res += "^{" + str(curr_exp) + "}"
                    if curr_exp > 0:
                        res += r" \, "
                    curr_exp = 1
                    res += (r"\Gamma_{" + field + "}(s" +
                            seriescoeff(elt, 0, "signed", "", 3) + ")")
            if curr_exp > 1:
                res += "^{" + str(curr_exp) + "}"
            if res != "":
                res += r" \, "
            return res

        ans += munu_str(mu_list, r"\R")
        ans += munu_str(nu_list, r"\C")
        ans += texname + r"\cr"
        ans += r"=\mathstrut & "
        if L.sign == 0:
            ans += r"\epsilon \cdot "
        else:
            ans += seriescoeff(L.sign, 0, "factor", "", 3) + r"\,"
        ans += tex_name_1ms
        if L.sign == 0 and L.degree == 1:
            ans += r"\quad (\text{with }\epsilon \text{ not computed})"
        if L.sign == 0 and L.degree > 1:
            ans += r"\quad (\text{with }\epsilon \text{ unknown})"
        ans += r"\end{aligned}"
    elif fmt == "selberg":
        ans += "(" + str(int(L.degree)) + r",\ "
        if L.level >= 10**8 and not is_prime(int(L.level)):
            ans += latex(L.level_factored)
        else:
            ans += str(int(L.level))
        ans += r",\ "
        ans += "("

        # this is mostly a hack for GL2 Maass forms
        def real_digits(x):
            return len(str(x).replace(".", "").lstrip("-").lstrip("0"))

        def mu_fe_prec(x):
            if L._Ltype == "maass":
                return real_digits(imag_part(x))
            else:
                return 3

        if L.mu_fe != []:
            mus = [
                display_complex(CDF(mu).real(),
                                CDF(mu).imag(),
                                mu_fe_prec(mu),
                                method="round") for mu in L.mu_fe
            ]
            if len(mus) >= 6 and mus == [mus[0]] * len(mus):
                ans += "[%s]^{%d}" % (mus[0], len(mus))
            else:
                ans += ", ".join(mus)
        else:
            ans += r"\ "
        ans += ":"
        if L.nu_fe != []:
            if len(L.nu_fe) >= 6 and L.nu_fe == [L.nu_fe[0]] * len(L.nu_fe):
                ans += "[%s]^{%d}" % (L.nu_fe[0], len(L.nu_fe))
            else:
                ans += ", ".join(map(str, L.nu_fe))
        else:
            ans += r"\ "
        ans += r"),\ "
        ans += seriescoeff(L.sign, 0, "literal", "", 3)
        ans += ")"

    return ans
예제 #16
0
파일: lll.py 프로젝트: zined/35c3ctf-challs
    n = A.ncols()
    A = list(matrix(ZZ, A))
    for i in range(n):
        A.append([0]*i + [mod] + [0]*(n-i-1))

    L = matrix(ZZ, A).LLL()
    W1 = L*vector(ZZ, y)
    W2 = vector([int(round(RR(w)/mod))*mod - w for w in W1])
    return L.solve_right(W2) + y


if __name__ == "__main__":
    test = 0
    while True:
        print '  Testing heterogenous LGS mod composite'
        # from secrets import key
        # p = 2**126
        # p = 2**135
        p = 21652247421304131782679331804390761485569
        assert not is_prime(p)
        Zp = Integers(p)

        n = 40 # num vars
        m = n-1 # num equations

        x = vector([randrange(lo) for _ in range(n)])
        A = matrix([[randrange(lo) for _ in range(n)] for _ in range(m)])
        c = vector(ZZ,matrix(Zp,A)*x)
        assert x == small_lgs2(A, c, p)
예제 #17
0
from sage.all import MatrixSpace, matrix, VectorSpace, vector, \
    is_prime, GF

CHARSET = "abcdefghijklmnopqrstuvwxyz01345678{}_"
p = len(CHARSET)
assert is_prime(p)
Fp = GF(p)


def double_char_to_vector(s):
    assert len(s) == 2
    return vector(Fp, [CHARSET.index(s[0]), CHARSET.index(s[1])])


def vector_to_double_char(v):
    assert len(v) == 2
    return CHARSET[v[0]] + CHARSET[v[1]]


def encrypt(msg, K):
    assert all(c in CHARSET for c in msg)
    assert len(msg) % 2 == 0

    A, v = K
    ciphertext = ""
    for i in range(0, len(msg), 2):
        tmp = A * double_char_to_vector(msg[i:i + 2]) + v
        ciphertext += vector_to_double_char(tmp)

    return ciphertext
예제 #18
0
파일: Bsets.py 프로젝트: s-opitz/sfqm
def B(M,m, algorithm='theorem',rec=True,dict=False):
    if algorithm == 'bf':
        return Bbf(M,m)
    elif not algorithm == 'theorem':
        raise ValueError('algorithm has to be one of "theorem" and "bf" (for brute force)')
    Bs = list()
    if not is_prime(m):
        raise ValueError('m is supposed to be prime (general case: TODO)')
    p = m

    if isinstance(M,FiniteQuadraticModule_ambient):
        sym_M = genus_symbol_string_to_dict(M.jordan_decomposition().genus_symbol())
    elif isinstance(M, str):
        if len(M)>0:
            sym_M = genus_symbol_string_to_dict(M)
        else:
            sym_M = {}
    else:
        raise ValueError('M needs to be a "FiniteQuadraticModule" or a "str".')
    if not sym_M.has_key(p):
        sym_M[p]=list()
    #print sym_M
    #sym_M = get_genus_symbol_dict(M)

    if p == 2:
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1,2,7,0,0])
        Bs.append(sym_new)
        print sym_new, dict_to_genus_symbol_string(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1,2,7,1,0])
        Bs.append(sym_new)
        print sym_new, dict_to_genus_symbol_string(sym_new)
        for s in sym_M[p]:
            print s
            t=s[3]
            print t
            if rec:
                for ss in sym_M[p]:
                    if t==1 and ss[0]==s[0]+1:
                        sym_new=deepcopy(sym_M)
                        sym_new[p].remove(s)
                        if s[2] in [1,5]:
                            s2n = s[2]+2
                        else:
                            s2n = s[2]-2
                        sym_new[p].append([s[0],s[1],s2n,s[3],(s[4]+2)%8])
                        sym_new[p].remove(ss)
                        if ss[2] in [1,5]:
                            ss2n = ss[2]+2
                        else:
                            ss2n = ss[2]-2
                        sym_new[p].append([ss[0],ss[1],ss2n,ss[3],(ss[4]+2)%8])
                        Br = B(dict_to_genus_symbol_string(sym_new),p,rec=False,dict=True)
                        print "Br=", B(dict_to_genus_symbol_string(sym_new),p,rec=False,dict=True)
                        Bs = Bs+Br
            if s[1]>2 or t == 0 or t == None:
                # q^+2 type II -> (2q)^+2 type II
                if s[1] > 2 or s[4]==0:
                    print "rule q^+2 -> (2q)^+2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,7,0,0])
                    if s[1] > 2: sym_new[p].append([s[0],s[1]-2,-s[2],s[3],s[4]])
                    Bs.append(sym_new)
                    print dict_to_genus_symbol_string(sym_new)
                # q^-2 -> (2q)_4^-2
                if s[1] > 2 or s[4]==4:
                    print "rule q^-2 -> (2q)_4^-2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,3,1,4])
                    if s[1] > 2: sym_new[p].append([s[0],s[1]-2,(s[2]*3) % 8, s[3], (s[4]+4) % 8])
                    Bs.append(sym_new)
                    print sym_new, dict_to_genus_symbol_string(sym_new)
                # q^+2 -> (2q)_0^+2
                if s[1] > 2 or s[4]==0:
                    print "rule q^+2 -> (2q)_0^+2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,7,1,0])
                    if s[1] > 2: sym_new[p].append([s[0],s[1]-2,-s[2],s[3],s[4]])
                    Bs.append(sym_new)
                    print dict_to_genus_symbol_string(sym_new)
            if t == 1:
                print "t=1"
                #rule for odd type, mult 1 power up
                odds = [1,3,5,7]
                for o in odds:
                    if (s[1] == 1 and (s[4]==o or s[0]==1 and s[4] % 8 == (o+4) %8)) \
                           or s[1]>3 \
                           or (s[1]==3 and not ((s[4]-o) % 8 ) in [4,6] and kronecker(s[2]*o,2) % 8 == 1) \
                           or (s[1]==2 and (s[4]-o) % 8 in odds):
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0]+2,1,o,1,o])
                        if s[1] > 1:
                                sym_new[p].append([s[0],s[1]-1,s[2]*o,1,(s[4]-o) % 8])
                        print dict_to_genus_symbol_string(sym_new)
                        Bs.append(sym_new)
                print s[1]
                if s[1] >= 2:
                    print s
                    if s[4] == 0 or (s[0]==1 and s[4]==4):
                        print "1,4"
                        print sym_M
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0]+1,2,7,0,0])
                        if s[1]>2:
                            sym_new[p].append([s[0],s[1]-2,(-s[2]) % 8, 1, s[4]])
                        Bs.append(sym_new)
                        print sym_new
                        print dict_to_genus_symbol_string(sym_new)
                    if s[4] == 4:
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0]+1,2,3,0,4])
                        if s[1]>2:
                            sym_new[p].append([s[0],s[1]-2,(s[2]*3) % 8, 1, (s[4]-4)%8])
                        Bs.append(sym_new)
                        print sym_new
                if s[1]>2 and s[1] % 2 == 0:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,s[2],0,s[4]])
                    sym_new[p].append([s[0],s[1]-2,0,0,0])
                    Bs.append(sym_new)
        
    else:
        ep = -1 if p % 4 == 3 else 1
        if not sym_M.has_key(p):
            sym_M[p]=list()
        #rule 1+2 for triv p-module
        sym_new = deepcopy(sym_M)
        sym_new[p].append([2,1,1])
        Bs.append(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([2,1,-1])
        Bs.append(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1,2,ep])
        Bs.append(sym_new)
        for s in sym_M[p]:
            sym_new = deepcopy(sym_M)
            sym_new[p].remove(s)
            #rule 1 (power+2, mult 1)
            sym_new[p].append([s[0]+2,1,s[2]])
            if s[1] > 1:
                sym_new[p].append([s[0],s[1]-1,1])
                Bs.append(sym_new)
                sym_new = deepcopy(sym_M)
                sym_new[p].remove(s)
                sym_new[p].append([s[0]+2,1,-s[2]])
                sym_new[p].append([s[0],s[1]-1,-1])
                Bs.append(sym_new)
            else:
                Bs.append(sym_new)
            #rule 2 (power+1, mult 2)
            if s[1] >= 2:
                if s[1]==2 and s[2]==ep:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,ep])
                    Bs.append(sym_new)
                elif s[1]>2:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0]+1,2,ep])
                    sym_new[p].append([s[0],s[1]-2,ep*s[2]])
                    Bs.append(sym_new)
    if dict:
        return Bs
    Bss = list()
    for sym in Bs:
        sym = reduce_symbol(sym)
        sym = dict_to_genus_symbol_string(sym)
        Bss.append(sym)
    if p == 2:
        Bs = list()
        for s in Bss:
            try:
                FiniteQuadraticModule(s)
                Bs.append(s)
            except:
                print "ERROR: ", s
        Bss = Bs
        print "Bs = ", Bs
        #mods_uniq=list()
        #for M in mods:                               
        #    seen = False                                 
        #    for N in mods_uniq:
        #        if N.is_isomorphic(M):
        #            seen = True
        #    if not seen:
        #        mods_uniq.append(M)
        #Bss = [M.jordan_decomposition().genus_symbol() for M in mods_uniq]
    return Bss
예제 #19
0
    def general_webpagedata(self):
        info = {}
        try:
            info['support'] = self.support
        except AttributeError:
            info['support'] = ''

        info['Ltype'] = self.Ltype()

        try:
            info['label'] = self.label
        except AttributeError:
            info['label'] = ""

        try:
            info['credit'] = self.credit
        except AttributeError:
            info['credit'] = ""

        info['degree'] = int(self.degree)
        info['conductor'] = self.level
        if not is_prime(int(self.level)) and int(self.level) != 1:
            if self.level >= 10**8:
                info['conductor'] = latex(self.level_factored)
            else:
                info['conductor_factored'] = latex(self.level_factored)
        if self.analytic_conductor:
            info['analytic_conductor'] = display_float(
                self.analytic_conductor,
                6,
                extra_truncation_digits=40,
                latex=True)
            info['root_analytic_conductor'] = display_float(
                self.root_analytic_conductor,
                6,
                extra_truncation_digits=40,
                latex=True)
        else:
            info['analytic_conductor'] = self.analytic_conductor
            info['root_analytic_conductor'] = self.root_analytic_conductor
        if self.rational is not None:
            info['rational'] = 'yes' if self.rational else 'no'

        info['sign'] = "$" + styleTheSign(self.sign) + "$"
        info['algebraic'] = self.algebraic
        info['arithmetic'] = 'yes' if self.arithmetic else 'no'
        if self.selfdual:
            info['selfdual'] = 'yes'
        else:
            info['selfdual'] = 'no'
        if self.primitive:
            info['primitive'] = 'yes'
        else:
            info['primitive'] = 'no'
        info['dirichlet'] = lfuncDShtml(self, "analytic")
        # Hack, fix this more general?
        info['dirichlet'] = info['dirichlet'].replace('*I', '<em>i</em>')

        info['eulerproduct'] = lfuncEPtex(self, "abstract")
        info['functionalequation'] = lfuncFEtex(self, "analytic")
        info['functionalequationSelberg'] = lfuncFEtex(self, "selberg")

        if hasattr(self, 'positive_zeros'):
            info['positive_zeros'] = self.positive_zeros
            info['negative_zeros'] = self.negative_zeros

        if hasattr(self, 'plot'):
            info['plot'] = self.plot

        if hasattr(self, 'factorization'):
            info['factorization'] = self.factorization

        if self.fromDB and self.algebraic:
            info['dirichlet_arithmetic'] = lfuncDShtml(self, "arithmetic")
            info['eulerproduct_arithmetic'] = lfuncEPtex(self, "arithmetic")
            info['functionalequation_arithmetic'] = lfuncFEtex(
                self, "arithmetic")

            if self.motivic_weight % 2 == 0:
                arith_center = "\\frac{" + str(1 +
                                               self.motivic_weight) + "}{2}"
            else:
                arith_center = str(ZZ(1) / 2 + self.motivic_weight / 2)
            svt_crit = specialValueTriple(self, 0.5, '\\frac12', arith_center)
            info['sv_critical'] = svt_crit[0] + "\\ =\\ " + svt_crit[2]
            info['sv_critical_analytic'] = [
                svt_crit[0],
                scientific_notation_helper(svt_crit[2])
            ]
            info['sv_critical_arithmetic'] = [
                svt_crit[1],
                scientific_notation_helper(svt_crit[2])
            ]

            if self.motivic_weight % 2 == 1:
                arith_edge = "\\frac{" + str(2 + self.motivic_weight) + "}{2}"
            else:
                arith_edge = str(ZZ(1) + self.motivic_weight / 2)

            svt_edge = specialValueTriple(self, 1, '1', arith_edge)
            info['sv_edge'] = svt_edge[0] + "\\ =\\ " + svt_edge[2]
            info['sv_edge_analytic'] = [
                svt_edge[0],
                scientific_notation_helper(svt_edge[2])
            ]
            info['sv_edge_arithmetic'] = [
                svt_edge[1],
                scientific_notation_helper(svt_edge[2])
            ]

            chilatex = r"$\chi_{" + str(self.charactermodulus) + "} (" + str(
                self.characternumber) + r", \cdot )$"
            info['chi'] = ''
            if self.charactermodulus != self.level:
                info['chi'] += "induced by "
            info['chi'] += '<a href="' + url_for(
                'characters.render_Dirichletwebpage',
                modulus=self.charactermodulus,
                number=self.characternumber)
            info['chi'] += '">' + chilatex + '</a>'

            info['st_group'] = self.st_group
            info['st_link'] = self.st_link
            info['rank'] = self.order_of_vanishing
            info['motivic_weight'] = r'\(%d\)' % self.motivic_weight

        elif self.Ltype() == "riemann":
            info['sv_edge'] = r"\[\zeta(1) \approx $\infty$\]"
            info['sv_critical'] = r"\[\zeta(1/2) \approx -1.460354508\]"

        elif self.Ltype() != "artin" or (self.Ltype() == "artin"
                                         and self.sign != 0):
            try:
                info['sv_edge'] = specialValueString(self, 1, '1')
                info['sv_critical'] = specialValueString(self, 0.5, '1/2')
            except Exception:
                info['sv_critical'] = "L(1/2): not computed"
                info['sv_edge'] = "L(1): not computed"

        return info
예제 #20
0
 def primes(self, primes, test=True):
     self._primes = primes
     if test:
         for p in primes:
             if not is_prime(p):
                 self._primes.remove(p)
예제 #21
0
파일: Bsets.py 프로젝트: s-opitz/sfqm
def B(M, m, algorithm='theorem', rec=True, dict=False):
    if algorithm == 'bf':
        return Bbf(M, m)
    elif not algorithm == 'theorem':
        raise ValueError(
            'algorithm has to be one of "theorem" and "bf" (for brute force)')
    Bs = list()
    if not is_prime(m):
        raise ValueError('m is supposed to be prime (general case: TODO)')
    p = m

    if isinstance(M, FiniteQuadraticModule_ambient):
        sym_M = genus_symbol_string_to_dict(
            M.jordan_decomposition().genus_symbol())
    elif isinstance(M, str):
        if len(M) > 0:
            sym_M = genus_symbol_string_to_dict(M)
        else:
            sym_M = {}
    else:
        raise ValueError('M needs to be a "FiniteQuadraticModule" or a "str".')
    if not sym_M.has_key(p):
        sym_M[p] = list()
    #print sym_M
    #sym_M = get_genus_symbol_dict(M)

    if p == 2:
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1, 2, 7, 0, 0])
        Bs.append(sym_new)
        print sym_new, dict_to_genus_symbol_string(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1, 2, 7, 1, 0])
        Bs.append(sym_new)
        print sym_new, dict_to_genus_symbol_string(sym_new)
        for s in sym_M[p]:
            print s
            t = s[3]
            print t
            if rec:
                for ss in sym_M[p]:
                    if t == 1 and ss[0] == s[0] + 1:
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        if s[2] in [1, 5]:
                            s2n = s[2] + 2
                        else:
                            s2n = s[2] - 2
                        sym_new[p].append(
                            [s[0], s[1], s2n, s[3], (s[4] + 2) % 8])
                        sym_new[p].remove(ss)
                        if ss[2] in [1, 5]:
                            ss2n = ss[2] + 2
                        else:
                            ss2n = ss[2] - 2
                        sym_new[p].append(
                            [ss[0], ss[1], ss2n, ss[3], (ss[4] + 2) % 8])
                        Br = B(dict_to_genus_symbol_string(sym_new),
                               p,
                               rec=False,
                               dict=True)
                        print "Br=", B(dict_to_genus_symbol_string(sym_new),
                                       p,
                                       rec=False,
                                       dict=True)
                        Bs = Bs + Br
            if s[1] > 2 or t == 0 or t == None:
                # q^+2 type II -> (2q)^+2 type II
                if s[1] > 2 or s[4] == 0:
                    print "rule q^+2 -> (2q)^+2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, 7, 0, 0])
                    if s[1] > 2:
                        sym_new[p].append([s[0], s[1] - 2, -s[2], s[3], s[4]])
                    Bs.append(sym_new)
                    print dict_to_genus_symbol_string(sym_new)
                # q^-2 -> (2q)_4^-2
                if s[1] > 2 or s[4] == 4:
                    print "rule q^-2 -> (2q)_4^-2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, 3, 1, 4])
                    if s[1] > 2:
                        sym_new[p].append([
                            s[0], s[1] - 2, (s[2] * 3) % 8, s[3],
                            (s[4] + 4) % 8
                        ])
                    Bs.append(sym_new)
                    print sym_new, dict_to_genus_symbol_string(sym_new)
                # q^+2 -> (2q)_0^+2
                if s[1] > 2 or s[4] == 0:
                    print "rule q^+2 -> (2q)_0^+2"
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, 7, 1, 0])
                    if s[1] > 2:
                        sym_new[p].append([s[0], s[1] - 2, -s[2], s[3], s[4]])
                    Bs.append(sym_new)
                    print dict_to_genus_symbol_string(sym_new)
            if t == 1:
                print "t=1"
                #rule for odd type, mult 1 power up
                odds = [1, 3, 5, 7]
                for o in odds:
                    if (s[1] == 1 and (s[4]==o or s[0]==1 and s[4] % 8 == (o+4) %8)) \
                           or s[1]>3 \
                           or (s[1]==3 and not ((s[4]-o) % 8 ) in [4,6] and kronecker(s[2]*o,2) % 8 == 1) \
                           or (s[1]==2 and (s[4]-o) % 8 in odds):
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0] + 2, 1, o, 1, o])
                        if s[1] > 1:
                            sym_new[p].append(
                                [s[0], s[1] - 1, s[2] * o, 1, (s[4] - o) % 8])
                        print dict_to_genus_symbol_string(sym_new)
                        Bs.append(sym_new)
                print s[1]
                if s[1] >= 2:
                    print s
                    if s[4] == 0 or (s[0] == 1 and s[4] == 4):
                        print "1,4"
                        print sym_M
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0] + 1, 2, 7, 0, 0])
                        if s[1] > 2:
                            sym_new[p].append(
                                [s[0], s[1] - 2, (-s[2]) % 8, 1, s[4]])
                        Bs.append(sym_new)
                        print sym_new
                        print dict_to_genus_symbol_string(sym_new)
                    if s[4] == 4:
                        sym_new = deepcopy(sym_M)
                        sym_new[p].remove(s)
                        sym_new[p].append([s[0] + 1, 2, 3, 0, 4])
                        if s[1] > 2:
                            sym_new[p].append([
                                s[0], s[1] - 2, (s[2] * 3) % 8, 1,
                                (s[4] - 4) % 8
                            ])
                        Bs.append(sym_new)
                        print sym_new
                if s[1] > 2 and s[1] % 2 == 0:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, s[2], 0, s[4]])
                    sym_new[p].append([s[0], s[1] - 2, 0, 0, 0])
                    Bs.append(sym_new)

    else:
        ep = -1 if p % 4 == 3 else 1
        if not sym_M.has_key(p):
            sym_M[p] = list()
        #rule 1+2 for triv p-module
        sym_new = deepcopy(sym_M)
        sym_new[p].append([2, 1, 1])
        Bs.append(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([2, 1, -1])
        Bs.append(sym_new)
        sym_new = deepcopy(sym_M)
        sym_new[p].append([1, 2, ep])
        Bs.append(sym_new)
        for s in sym_M[p]:
            sym_new = deepcopy(sym_M)
            sym_new[p].remove(s)
            #rule 1 (power+2, mult 1)
            sym_new[p].append([s[0] + 2, 1, s[2]])
            if s[1] > 1:
                sym_new[p].append([s[0], s[1] - 1, 1])
                Bs.append(sym_new)
                sym_new = deepcopy(sym_M)
                sym_new[p].remove(s)
                sym_new[p].append([s[0] + 2, 1, -s[2]])
                sym_new[p].append([s[0], s[1] - 1, -1])
                Bs.append(sym_new)
            else:
                Bs.append(sym_new)
            #rule 2 (power+1, mult 2)
            if s[1] >= 2:
                if s[1] == 2 and s[2] == ep:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, ep])
                    Bs.append(sym_new)
                elif s[1] > 2:
                    sym_new = deepcopy(sym_M)
                    sym_new[p].remove(s)
                    sym_new[p].append([s[0] + 1, 2, ep])
                    sym_new[p].append([s[0], s[1] - 2, ep * s[2]])
                    Bs.append(sym_new)
    if dict:
        return Bs
    Bss = list()
    for sym in Bs:
        sym = reduce_symbol(sym)
        sym = dict_to_genus_symbol_string(sym)
        Bss.append(sym)
    if p == 2:
        Bs = list()
        for s in Bss:
            try:
                FiniteQuadraticModule(s)
                Bs.append(s)
            except:
                print "ERROR: ", s
        Bss = Bs
        print "Bs = ", Bs
        #mods_uniq=list()
        #for M in mods:
        #    seen = False
        #    for N in mods_uniq:
        #        if N.is_isomorphic(M):
        #            seen = True
        #    if not seen:
        #        mods_uniq.append(M)
        #Bss = [M.jordan_decomposition().genus_symbol() for M in mods_uniq]
    return Bss
예제 #22
0
    def general_webpagedata(self):
        info = {}
        try:
            info['support'] = self.support
        except AttributeError:
            info['support'] = ''

        info['Ltype'] = self.Ltype()
        info['label'] = self.label
        info['credit'] = self.credit

        info['degree'] = int(self.degree)
        info['conductor'] = self.level
        if not is_prime(int(self.level)):
            info['conductor_factored'] = latex(factor(int(self.level)))

        info['sign'] = "$" + styleTheSign(self.sign) + "$"
        info['algebraic'] = self.algebraic
        if self.selfdual:
            info['selfdual'] = 'yes'
        else:
            info['selfdual'] = 'no'
        if self.primitive:
            info['primitive'] = 'yes'
        else:
            info['primitive'] = 'no'
        info['dirichlet'] = lfuncDShtml(self, "analytic")
        # Hack, fix this more general?
        info['dirichlet'] = info['dirichlet'].replace('*I','<em>i</em>')
        
        info['eulerproduct'] = lfuncEPtex(self, "abstract")
        info['functionalequation'] = lfuncFEtex(self, "analytic")
        info['functionalequationSelberg'] = lfuncFEtex(self, "selberg")

        if hasattr(self, 'positive_zeros'):
            info['positive_zeros'] = self.positive_zeros
            info['negative_zeros'] = self.negative_zeros

        if hasattr(self, 'plot'):
            info['plot'] = self.plot

        if hasattr(self, 'factorization'):
            info['factorization'] = self.factorization
            
        if self.fromDB and self.algebraic:
            info['dirichlet_arithmetic'] = lfuncDShtml(self, "arithmetic")
            info['eulerproduct_arithmetic'] = lfuncEPtex(self, "arithmetic")
            info['functionalequation_arithmetic'] = lfuncFEtex(self, "arithmetic")

            if self.motivic_weight % 2 == 0:
               arith_center = "\\frac{" + str(1 + self.motivic_weight) + "}{2}"
            else:
               arith_center = str(ZZ(1)/2 + self.motivic_weight/2)
            svt_crit = specialValueTriple(self, 0.5, '\\frac12',arith_center)
            info['sv_critical'] = svt_crit[0] + "\\ =\\ " + svt_crit[2]
            info['sv_critical_analytic'] = [svt_crit[0], svt_crit[2]]
            info['sv_critical_arithmetic'] = [svt_crit[1], svt_crit[2]]

            if self.motivic_weight % 2 == 1:
               arith_edge = "\\frac{" + str(2 + self.motivic_weight) + "}{2}"
            else:
               arith_edge = str(ZZ(1) + self.motivic_weight/2)

            svt_edge = specialValueTriple(self, 1, '1',arith_edge)
            info['sv_edge'] = svt_edge[0] + "\\ =\\ " + svt_edge[2]
            info['sv_edge_analytic'] = [svt_edge[0], svt_edge[2]]
            info['sv_edge_arithmetic'] = [svt_edge[1], svt_edge[2]]

            info['st_group'] = self.st_group
            info['st_link'] = self.st_link
            info['rank'] = self.order_of_vanishing
            info['motivic_weight'] = self.motivic_weight
        
        elif self.Ltype() != "artin" or (self.Ltype() == "artin" and self.sign != 0):
            try:
                info['sv_edge'] = specialValueString(self, 1, '1')
                info['sv_critical'] = specialValueString(self, 0.5, '1/2')
            except:
                info['sv_critical'] = "L(1/2): not computed"
                info['sv_edge'] = "L(1): not computed"

        return info
예제 #23
0
파일: lll.py 프로젝트: niklasb/ctf-tools
        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)

        assert xs == small_lgs(A, mod=p)
        assert xs == small_lgs2(A, c=None, mod=p)

        print '  Testing homogenous LGS modulo composite'
        hi = 2**128
        lo = 2**100
        p = hi + 1
        assert not is_prime(p)

        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)
예제 #24
0
import sys
import itertools
from sage.all import is_prime, factor
N = 32
J = 500
out = 'Case #1:\n'
found = 0
for i in itertools.product('01',repeat=N-2):
    n = '1'+''.join(i)+'1'
    l = []
    for j in range(2,11):
        if is_prime(int(n,j)):
            break
        l.append(str(factor(int(n,j))[0][0]))
    else:
        print("found",n,l)
        out += '{} {}\n'.format(n,' '.join(l))
        found += 1
        if found >= J:
            break
open('C.out','w').write(out)
예제 #25
0
def elliptic_curve_search(info, query):
    parse_rational_to_list(info, query, 'jinv', 'j-invariant')
    parse_ints(info, query, 'conductor')
    if info.get('conductor_type'):
        if info['conductor_type'] == 'prime':
            query['num_bad_primes'] = 1
            query['semistable'] = True
        elif info['conductor_type'] == 'prime_power':
            query['num_bad_primes'] = 1
        elif info['conductor_type'] == 'squarefree':
            query['semistable'] = True
        elif info['conductor_type'] == 'divides':
            if not isinstance(query.get('conductor'), int):
                err = "You must specify a single conductor"
                flash_error(err)
                raise ValueError(err)
            else:
                query['conductor'] = {'$in': integer_divisors(ZZ(query['conductor']))}
    parse_signed_ints(info, query, 'discriminant', qfield=('signD', 'absD'))
    parse_ints(info,query,'rank')
    parse_ints(info,query,'sha','analytic order of &#1064;')
    parse_ints(info,query,'num_int_pts','num_int_pts')
    parse_ints(info,query,'class_size','class_size')
    if info.get('class_deg'):
        parse_ints(info,query,'class_deg','class_deg')
        if not isinstance(query.get('class_deg'), int):
            err = "You must specify a single isogeny class degree"
            flash_error(err)
            raise ValueError(err)
    parse_floats(info,query,'regulator','regulator')
    parse_floats(info, query, 'faltings_height', 'faltings_height')
    if info.get('reduction'):
        if info['reduction'] == 'semistable':
            query['semistable'] = True
        elif info['reduction'] == 'not semistable':
            query['semistable'] = False
        elif info['reduction'] == 'potentially good':
            query['potential_good_reduction'] = True
        elif info['reduction'] == 'not potentially good':
            query['potential_good_reduction'] = False
    if info.get('torsion'):
        if info['torsion'][0] == '[':
            parse_bracketed_posints(info,query,'torsion',qfield='torsion_structure',maxlength=2,check_divisibility='increasing')
        else:
            parse_ints(info,query,'torsion')
    # speed up slow torsion_structure searches by also setting torsion
    #if 'torsion_structure' in query and not 'torsion' in query:
    #    query['torsion'] = reduce(mul,[int(n) for n in query['torsion_structure']],1)
    if 'cm' in info:
        if info['cm'] == 'noCM':
            query['cm'] = 0
        elif info['cm'] == 'CM':
            query['cm'] = {'$ne' : 0}
        else:
            parse_ints(info,query,field='cm',qfield='cm')
    parse_element_of(info,query,'isogeny_degrees',split_interval=200,contained_in=get_stats().isogeny_degrees)
    parse_primes(info, query, 'nonmax_primes', name='non-maximal primes',
                 qfield='nonmax_primes', mode=info.get('nonmax_quantifier'), radical='nonmax_rad')
    parse_primes(info, query, 'bad_primes', name='bad primes',
                 qfield='bad_primes',mode=info.get('bad_quantifier'))
    parse_primes(info, query, 'sha_primes', name='sha primes',
                 qfield='sha_primes',mode=info.get('sha_quantifier'))
    if info.get('galois_image'):
        labels = [a.strip() for a in info['galois_image'].split(',')]
        elladic_labels = [a for a in labels if elladic_image_label_regex.fullmatch(a) and is_prime_power(elladic_image_label_regex.match(a)[1])]
        modell_labels = [a for a in labels if modell_image_label_regex.fullmatch(a) and is_prime(modell_image_label_regex.match(a)[1])]
        if len(elladic_labels)+len(modell_labels) != len(labels):
            err = "Unrecognized Galois image label, it should be the label of a subgroup of GL(2,Z_ell), such as %s, or the label of a subgroup of GL(2,F_ell), such as %s, or a list of such labels"
            flash_error(err, "13.91.3.2", "13S4")
            raise ValueError(err)
        if elladic_labels:
            query['elladic_images'] = {'$contains': elladic_labels}
        if modell_labels:
            query['modell_images'] = {'$contains': modell_labels}
        if 'cm' not in query:
            query['cm'] = 0
            info['cm'] = "noCM"
        if query['cm']:
            # try to help the user out if they specify the normalizer of a Cartan in the CM case (these are either maximal or impossible
            if any(a.endswith("Nn") for a in modell_labels) or any(a.endswith("Ns") for a in modell_labels):
                err = "To search for maximal images, exclude non-maximal primes"
                flash_error(err)
                raise ValueError(err)
        else:
            # if the user specifies full mod-ell image with ell > 3, automatically exclude nonmax primes (if possible)
            max_labels = [a for a in modell_labels if a.endswith("G") and int(modell_image_label_regex.match(a)[1]) > 3]
            if max_labels:
                if info.get('nonmax_primes') and info['nonmax_quantifier'] != 'exclude':
                    err = "To search for maximal images, exclude non-maximal primes"
                    flash_error(err)
                    raise ValueError(err)
                else:
                    modell_labels = [a for a in modell_labels if a not in max_labels]
                    max_primes = [modell_image_label_regex.match(a)[1] for a in max_labels]
                    if info.get('nonmax_primes'):
                        max_primes += [l.strip() for l in info['nonmax_primes'].split(',') if not l.strip() in max_primes]
                    max_primes.sort(key=int)
                    info['nonmax_primes'] = ','.join(max_primes)
                    info['nonmax_quantifier'] = 'exclude'
                    parse_primes(info, query, 'nonmax_primes', name='non-maximal primes',
                                 qfield='nonmax_primes', mode=info.get('nonmax_quantifier'), radical='nonmax_rad')
                    info['galois_image'] = ','.join(modell_labels + elladic_labels)
                query['modell_images'] = { '$contains': modell_labels }

    # The button which used to be labelled Optimal only no/yes"
    # (default: no) has been renamed "Curves per isogeny class
    # all/one" (default: all).  When this option is "one" we only list
    # one curve in each class, currently choosing the curve with
    # minimal Faltings heights, which is conjecturally the
    # Gamma_1(N)-optimal curve.
    if 'optimal' in info and info['optimal'] == 'on':
        query["__one_per__"] = "lmfdb_iso"

    info['curve_ainvs'] = lambda dbc: str([ZZ(ai) for ai in dbc['ainvs']])
    info['curve_url_LMFDB'] = lambda dbc: url_for(".by_triple_label", conductor=dbc['conductor'], iso_label=split_lmfdb_label(dbc['lmfdb_iso'])[1], number=dbc['lmfdb_number'])
    info['iso_url_LMFDB'] = lambda dbc: url_for(".by_double_iso_label", conductor=dbc['conductor'], iso_label=split_lmfdb_label(dbc['lmfdb_iso'])[1])
    info['cremona_bound'] = CREMONA_BOUND
    info['curve_url_Cremona'] = lambda dbc: url_for(".by_ec_label", label=dbc['Clabel'])
    info['iso_url_Cremona'] = lambda dbc: url_for(".by_ec_label", label=dbc['Ciso'])
    info['FH'] = lambda dbc: RealField(20)(dbc['faltings_height'])
예제 #26
0
def lfuncFEtex(L, fmt):
    """ Returns the LaTex for displaying the Functional equation of the L-function L.
        fmt could be any of the values: "analytic", "selberg"
    """
    if fmt == "arithmetic":
        mu_list = [mu - L.motivic_weight/2 for mu in L.mu_fe]
        nu_list = [nu - L.motivic_weight/2 for nu in L.nu_fe]
        mu_list.sort()
        nu_list.sort()
        texname = L.texname_arithmetic
        try:
            tex_name_s = L.texnamecompleteds_arithmetic
            tex_name_1ms = L.texnamecompleted1ms_arithmetic
        except AttributeError:
            tex_name_s = L.texnamecompleteds
            tex_name_1ms = L.texnamecompleted1ms

    else:
        mu_list = L.mu_fe[:]
        nu_list = L.nu_fe[:]
        texname = L.texname
        tex_name_s = L.texnamecompleteds
        tex_name_1ms = L.texnamecompleted1ms
    ans = ""
    if fmt == "arithmetic" or fmt == "analytic":
        ans = "\\begin{align}\n" + tex_name_s + "=\\mathstrut &"
        if L.level > 1:
            if L.level >= 10**8 and not is_prime(int(L.level)):
                ans += r"\left(%s\right)^{s/2}" % latex(L.level_factored)
            else:
                ans += latex(L.level) + "^{s/2}"
            ans += " \\, "
        def munu_str(factors_list, field):
            assert field in ['\R','\C']
            # set up to accommodate multiplicity of Gamma factors
            old = ""
            res = ""
            curr_exp = 0
            for elt in factors_list:
                if elt == old:
                    curr_exp += 1
                else:
                    old = elt
                    if curr_exp > 1:
                        res += "^{" + str(curr_exp) + "}"
                    if curr_exp > 0:
                        res += " \\, "
                    curr_exp = 1
                    res += "\Gamma_{" + field + "}(s" + seriescoeff(elt, 0, "signed", "", 3) + ")"
            if curr_exp > 1:
                res += "^{" + str(curr_exp) + "}"
            if res != "":
                res +=  " \\, "
            return res
        ans += munu_str(mu_list, '\R')
        ans += munu_str(nu_list, '\C')
        ans += texname + "\\cr\n"
        ans += "=\\mathstrut & "
        if L.sign == 0:
            ans += "\epsilon \cdot "
        else:
            ans += seriescoeff(L.sign, 0, "factor", "", 3) + "\\,"
        ans += tex_name_1ms
        if L.sign == 0 and L.degree == 1:
            ans += "\quad (\\text{with }\epsilon \\text{ not computed})"
        if L.sign == 0 and L.degree > 1:
            ans += "\quad (\\text{with }\epsilon \\text{ unknown})"
        ans += "\n\\end{align}\n"
    elif fmt == "selberg":
        ans += "(" + str(int(L.degree)) + ",\\ "
        if L.level >= 10**8 and not is_prime(int(L.level)):
            ans += latex(L.level_factored)
        else:
            ans += str(int(L.level))
        ans += ",\\ "
        ans += "("
        # this is mostly a hack for GL2 Maass forms
        def real_digits(x):
            return len(str(x).replace('.','').lstrip('-').lstrip('0'))
        def mu_fe_prec(x):
            if L._Ltype == 'maass':
                return real_digits(imag_part(x))
            else:
                return 3
        if L.mu_fe != []:
            mus = [ display_complex(CDF(mu).real(), CDF(mu).imag(),  mu_fe_prec(mu), method="round" ) for mu in L.mu_fe ]
            if len(mus) >= 6 and mus == [mus[0]]*len(mus):
                ans += '[%s]^{%d}' % (mus[0], len(mus))
            else:
                ans += ", ".join(mus)
        else:
            ans += "\\ "
        ans += ":"
        if L.nu_fe != []:
            if len(L.nu_fe) >= 6 and L.nu_fe == [L.nu_fe[0]]*len(L.nu_fe):
                ans += '[%s]^{%d}' % (L.nu_fe[0], len(L.nu_fe))
            else:
                ans += ", ".join(map(str, L.nu_fe))
        else:
            ans += "\\ "
        ans += "),\\ "
        ans += seriescoeff(L.sign, 0, "literal", "", 3)
        ans += ")"

    return(ans)
예제 #27
0
    def general_webpagedata(self):
        info = {}
        try:
            info['support'] = self.support
        except AttributeError:
            info['support'] = ''

        info['Ltype'] = self.Ltype()
        info['label'] = self.label
        info['credit'] = self.credit

        info['degree'] = int(self.degree)
        info['conductor'] = self.level
        if not is_prime(int(self.level)):
            info['conductor_factored'] = latex(factor(int(self.level)))

        info['sign'] = "$" + styleTheSign(self.sign) + "$"
        info['algebraic'] = self.algebraic
        if self.selfdual:
            info['selfdual'] = 'yes'
        else:
            info['selfdual'] = 'no'
        if self.primitive:
            info['primitive'] = 'yes'
        else:
            info['primitive'] = 'no'
        info['dirichlet'] = lfuncDShtml(self, "analytic")
        # Hack, fix this more general?
        info['dirichlet'] = info['dirichlet'].replace('*I', '<em>i</em>')

        info['eulerproduct'] = lfuncEPtex(self, "abstract")
        info['functionalequation'] = lfuncFEtex(self, "analytic")
        info['functionalequationSelberg'] = lfuncFEtex(self, "selberg")

        if hasattr(self, 'positive_zeros'):
            info['positive_zeros'] = self.positive_zeros
            info['negative_zeros'] = self.negative_zeros

        if hasattr(self, 'plot'):
            info['plot'] = self.plot

        if hasattr(self, 'factorization'):
            info['factorization'] = self.factorization

        if self.fromDB and self.algebraic:
            info['dirichlet_arithmetic'] = lfuncDShtml(self, "arithmetic")
            info['eulerproduct_arithmetic'] = lfuncEPtex(self, "arithmetic")
            info['functionalequation_arithmetic'] = lfuncFEtex(
                self, "arithmetic")

            if self.motivic_weight % 2 == 0:
                arith_center = "\\frac{" + str(1 +
                                               self.motivic_weight) + "}{2}"
            else:
                arith_center = str(ZZ(1) / 2 + self.motivic_weight / 2)
            svt_crit = specialValueTriple(self, 0.5, '\\frac12', arith_center)
            info['sv_critical'] = svt_crit[0] + "\\ =\\ " + svt_crit[2]
            info['sv_critical_analytic'] = [svt_crit[0], svt_crit[2]]
            info['sv_critical_arithmetic'] = [svt_crit[1], svt_crit[2]]

            if self.motivic_weight % 2 == 1:
                arith_edge = "\\frac{" + str(2 + self.motivic_weight) + "}{2}"
            else:
                arith_edge = str(ZZ(1) + self.motivic_weight / 2)

            svt_edge = specialValueTriple(self, 1, '1', arith_edge)
            info['sv_edge'] = svt_edge[0] + "\\ =\\ " + svt_edge[2]
            info['sv_edge_analytic'] = [svt_edge[0], svt_edge[2]]
            info['sv_edge_arithmetic'] = [svt_edge[1], svt_edge[2]]

            info['st_group'] = self.st_group
            info['st_link'] = self.st_link
            info['rank'] = self.order_of_vanishing
            info['motivic_weight'] = self.motivic_weight

        elif self.Ltype() != "artin" or (self.Ltype() == "artin"
                                         and self.sign != 0):
            try:
                info['sv_edge'] = specialValueString(self, 1, '1')
                info['sv_critical'] = specialValueString(self, 0.5, '1/2')
            except:
                info['sv_critical'] = "L(1/2): not computed"
                info['sv_edge'] = "L(1): not computed"

        return info